프로그래머스/level 2
[프로그래머스] 행렬 테두리 회전하기
binaryJournalist
2022. 5. 12. 20:24
반응형
출처: 프로그래머스 코딩 테스트 연습, https://programmers.co.kr/learn/challenges
머리로는 뭔가 할 수 있을 듯 말듯한데
결국 구글의 도움을 받아야 했음
def solution(rows, columns, queries):
answer = []
box = []
for i in range(rows):
row = []
for j in range(columns):
row.append(columns * i + j + 1)
box.append(row)
for querie in queries:
행1, 열1, 행2, 열2 = querie
행1 -= 1; 열1 -= 1; 행2 -= 1; 열2 -= 1
tmp = box[행1][열1]
small = tmp
# left
for i in range(행1 + 1, 행2 + 1):
box[i-1][열1] = box[i][열1]
small = min(small, box[i][열1])
# bottom
for i in range(열1 + 1, 열2 + 1):
box[행2][i-1] = box[행2][i]
small = min(small, box[행2][i])
# right
for i in range(행2 - 1, 행1 - 1, -1):
box[i+1][열2] = box[i][열2]
small = min(small, box[i][열2])
# top
for i in range(열2 - 1, 열1 - 1, -1):
box[행1][i+1] = box[행1][i]
small = min(small, box[행1][i])
box[행1][열1+1] = tmp
answer.append(small)
return answer
참고:https://latte-is-horse.tistory.com/146
[프로그래머스 lv2] 행렬 테두리 회전하기 (파이썬)
2021 Dev-Matching:웹 백엔드 개발자(상반기) 문제입니다. 전체 소스코드는 맨 아래에 있습니다. 문제 설명 rows x columns 크기인 행렬이 있습니다. 행렬에는 1부터 rows x columns까지의 숫자가 한 줄씩 순서
latte-is-horse.tistory.com
더 좋은 코드를 발견해서 달아 놓음
def rotate(x1, y1, x2, y2, graph, answer):
# 오른쪽, 아래, 왼쪽, 위 순
dx = 0, 1, 0, -1
dy = 1, 0, -1, 0
d, x, y, tmp = 0, x1, y1, 10000
min_val = 10000
while d < 4:
nx = x + dx[d]
ny = y + dy[d]
min_val = min(min_val, graph[x][y])
# 범위 안인 경우
if x1 <= nx <= x2 and y1 <= ny <= y2:
graph[x][y], tmp = tmp, graph[x][y]
x, y = nx, ny
else:
d += 1
graph[x1][y1] = tmp
answer.append(min_val)
def solution(rows, columns, queries):
answer = []
graph = [[i + 1 for i in range(j * columns, (j + 1) * columns)] for j in range(rows)]
for query in queries:
x1, y1, x2, y2 = map(int, query)
rotate(x1 - 1, y1 - 1, x2 - 1, y2 - 1, graph, answer)
return answer
출처: https://intrepidgeeks.com/tutorial/rotate-programmer-matrix-border-python
반응형