https://school.programmers.co.kr/learn/courses/30/lessons/77485
행렬 테두리의 값을 deque에 넣고 회전한 다음,
테두리에 재할당하도록 했다.행렬 가로 세로 길이를 구하고, 순회하면서 테두리 값을 배열에 넣고
그 배열을 deque화 한다.deque를 회전하고 다시 재할당 한다.
from collections import deque
def solution(rows, columns, queries):
answer = []
board = [[i * columns + j + 1 for j in range(columns)] for i in range(rows)]
def selectTarget(querie):
y1, x1, y2, x2 = [i - 1 for i in querie]
target = []
cur_y, cur_x = y1, x1
size_y = y2 - y1 + 1
size_x = x2 - x1 + 1
for i in range(size_x):
target.append(board[cur_y][cur_x])
cur_x += 1
cur_y, cur_x = cur_y + 1, cur_x - 1
for i in range(size_y - 1):
target.append(board[cur_y][cur_x])
cur_y += 1
cur_y, cur_x = cur_y - 1, cur_x - 1
for i in range(size_x - 1):
target.append(board[cur_y][cur_x])
cur_x -= 1
cur_y, cur_x = cur_y - 1, cur_x + 1
for i in range(size_y - 2):
target.append(board[cur_y][cur_x])
cur_y -= 1
answer.append(min(target))
return target
def rotate(dq, querie):
dq.rotate(1)
y1, x1, y2, x2 = [i - 1 for i in querie]
cur_y, cur_x = y1, x1
size_y = y2 - y1 + 1
size_x = x2 - x1 + 1
index = 0
for i in range(size_x):
board[cur_y][cur_x] = dq[index]
cur_x += 1
index += 1
cur_y, cur_x = cur_y + 1, cur_x - 1
for i in range(size_y - 1):
board[cur_y][cur_x] = dq[index]
cur_y += 1
index += 1
cur_y, cur_x = cur_y - 1, cur_x - 1
for i in range(size_x - 1):
board[cur_y][cur_x] = dq[index]
cur_x -= 1
index += 1
cur_y, cur_x = cur_y - 1, cur_x + 1
for i in range(size_y - 2):
board[cur_y][cur_x] = dq[index]
cur_y -= 1
index += 1
for querie in queries:
dq = deque(selectTarget(querie))
rotate(dq, querie)
return answer
stack 을 활용한 풀이.
테두리 값을 배열에 넣고 배열 길이가 2개 이상일 때만 회전이 가능하니
맨뒤에서 두번째 값(이전값)으로 재할당 한다.
def solution(rows, columns, queries):
answer = []
board = [[i+(j)*columns for i in range(1,columns+1)] for j in range(rows)]
for a,b,c,d in queries:
stack = []
r1, c1, r2, c2 = a-1, b-1, c-1, d-1
for i in range(c1, c2+1):
stack.append(board[r1][i])
if len(stack) == 1:
continue
else:
board[r1][i] = stack[-2]
for j in range(r1+1, r2+1):
stack.append(board[j][i])
board[j][i] = stack[-2]
for k in range(c2-1, c1-1, -1):
stack.append(board[j][k])
board[j][k] = stack[-2]
for l in range(r2-1, r1-1, -1):
stack.append(board[l][k])
board[l][k] = stack[-2]
answer.append(min(stack))
return answer