[프로그래머스] 행렬 테두리 회전하기

이재윤·2025년 1월 30일
0

https://school.programmers.co.kr/learn/courses/30/lessons/77485

1) 코드

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

    num = 1
    board = []
    for i in range(rows):
        row = []
        for j in range(columns):
            row.append(num)
            num += 1
        board.append(row)

    dx = [0, 1, 0, -1]
    dy = [1, 0, -1, 0]

    for query in queries:
        x1, y1, x2, y2 = query[0], query[1], query[2], query[3]

        arr = []
        direction = 0
        x = x1-1
        y = y1-1
        arr.append(board[x][y])

        len1 = x2-x1+1
        len2 = y2-y1+1

        while True:
            nx = x + dx[direction]
            ny = y + dy[direction]

            if not (x1-1<=nx and nx <= x2-1 and y1-1<=ny and ny<=y2-1):
                direction += 1
                direction %= 4
                nx = x + dx[direction]
                ny = y + dy[direction]

            arr.append(board[nx][ny])

            x = nx
            y = ny

            if len(arr) == 2*len1+2*len2-4:
                break

        answer.append(min(arr))

        x = x1-1
        y = y1-1
        direction = 0

        while True:
            nx = x + dx[direction]
            ny = y + dy[direction]

            if not (x1-1<=nx and nx <= x2-1 and y1-1<=ny and ny<=y2-1):
                direction += 1
                direction %= 4
                nx = x + dx[direction]
                ny = y + dy[direction]

            num = arr.pop(0)
            board[nx][ny] = num

            x = nx
            y = ny

            if len(arr) == 0:
                break

    return answer

2) 해설

  • 기본적인 시뮬레이션 문제이다
    -> 요구사항대로 충실하게 구현해주면 된다.

0개의 댓글