Algorithm/programmers/2021 Dev-Matching: 웹 백엔드 개발자(상반기)/level2/ 행렬 테두리 회전하기(with python)

yellow·2021년 6월 22일
0

알고리즘 문제

목록 보기
50/58

📖 문제

📝 풀이 과정


1. 행렬을 회전시키기 전에, 회전시켜야 하는 요소들을 모두 리스트rotated_num 에 담아둔다.
2. 행렬을 회전시킬 때 북,동,남,서 방향으로 나누어서 차례차례 시계방향으로 한칸씩 회전시켰다.
2-1. 회전시키는 요소들 중 모서리에 있는 값 ((x1,y1), (x1,y2), (x2,y1), (x2,y2))들이 누락되지 않도록 d_tmp변수에 값을 미리 빼놓도록 했다.

⌨ 코드

def rotation(matrix, rows, columns, query):
    rotated_num = []
    x1, y1, x2, y2 = query[0], query[1], query[2], query[3]

    # 회전될 수들 모두 rotated_num에 담기
    for j in range(y1,y2):
        rotated_num.append(matrix[x1][j])
    for i in range(x1,x2):
        rotated_num.append(matrix[i][y2])
    for j in range(y2,y1,-1):
        rotated_num.append(matrix[x2][j])
    for i in range(x2,x1,-1):
        rotated_num.append(matrix[i][y1])

    # 회전
    # north
    east_tmp = matrix[x1][y2]
    for j in range(y2,y1,-1):
        matrix[x1][j] = matrix[x1][j-1]
        
    # east
    south_tmp = matrix[x2][y2]
    for i in range(x2,x1,-1):
        matrix[i][y2] = matrix[i-1][y2]
    matrix[x1+1][y2] = east_tmp

    # south
    west_tmp = matrix[x2][y1]
    for j in range(y1,y2):
        matrix[x2][j] = matrix[x2][j+1]
    matrix[x2][y2-1] = south_tmp

    # west
    for i in range(x1,x2):
        matrix[i][y1] = matrix[i+1][y1]
    matrix[x2-1][y1] = west_tmp

    # 회전된 수들 중 가장 작은 값을 리턴
    return min(rotated_num)


def solution(rows, columns, queries):
    answer = []

    # 행렬 구성하기
    matrix = [[0]*(columns+1) for _ in range(rows+1)]
    for i in range(1, rows+1):
        for j in range(1, columns+1):
            matrix[i][j] = (i-1)*columns + j

    for query in queries:
        answer.append(rotation(matrix, rows, columns, query))

    return answer

😊 느낀점

요즘 코딩 테스트를 준비하느라 포스트를 많이 올리지 못하는 중이지만, 오늘 푼 문제 중에 가장 오래 걸렸어서 가지고 와봤다.
문제 자체가 까다롭지는 않은데 행렬 인덱싱을 하는 게 번거롭고 헷갈렸다ㅠㅠ
이럴 때일수록 더 작은 기능 단위로 자를 수 있는지 고민해보고 예시를 생각하면서 하나씩 차근차근 풀어나가야 한다는 것 명심!!~~

profile
할 수 있어! :)

0개의 댓글