STUDY/Algorithm

[프로그래머스] 행렬 테두리 회전하기 python, 2021 Dev-Matching: 웹 백엔드 개발자(상반기)

sinawi95 2021. 5. 4. 21:37
728x90

programmers.co.kr/learn/courses/30/lessons/77485?language=python3

 

코딩테스트 연습 - 행렬 테두리 회전하기

6 6 [[2,2,5,4],[3,3,6,6],[5,1,6,3]] [8, 10, 25] 3 3 [[1,1,2,2],[1,2,2,3],[2,1,3,2],[2,2,3,3]] [1, 1, 5, 3]

programmers.co.kr

def solution(rows, columns, queries):
    answer = []
    min_val = rows * columns
    
    matrix = []
    old_val = 0
    for r in range(rows):
        tmp = list(range(old_val + 1, old_val + columns + 1)) 
        old_val += columns
        matrix.append(tmp)

    for sr, sc, er, ec in queries:
        min_val = rows * columns
        sr -= 1; sc -= 1; er -= 1; ec -= 1;
        tmp1, tmp2 = matrix[sr][sc], matrix[er][ec]
        min_val = min(min_val, tmp1, tmp2)
        for i in range(er - sr): # 좌,우
            min_val = min(min_val, matrix[sr + i + 1][sc], matrix[er - i - 1][ec])
            matrix[sr + i][sc] = matrix[sr + i + 1][sc] # 좌
            matrix[er - i][ec] = matrix[er - i - 1][ec] # 우
        
        for j in range(ec - sc): # 상,하
            min_val = min(min_val, matrix[sr][ec - j - 1], matrix[er][sc + j + 1])
            matrix[sr][ec - j] = matrix[sr][ec - j - 1] # 상
            matrix[er][sc + j] = matrix[er][sc + j + 1] # 하
        matrix[sr][sc + 1] = tmp1
        matrix[er][ec - 1] = tmp2
        answer.append(min_val)

    return answer

직접 돌려서 구현하였다.