출처 : 프로그래머스 코딩테스트 연습, https://programmers.co.kr/learn/courses/30/lessons/77485#
코딩테스트 연습 - 행렬 테두리 회전하기
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 rotate(arr, TL, BR, R, bound_length):
x1, y1 = TL
x2, y2 = BR
x = x1
y = y1
dx = [0, 1, 0, -1]
dy = [1, 0, -1, 0]
index = 0
bound_list = []
for _ in range(bound_length):
if x == x2 and y == y1:
index+=1
elif x == x2 and y == y2:
index+=1
elif x == x1 and y == y2:
index+=1
bound_list.append(arr[x][y])
x += dx[index]
y += dy[index]
bound_list = bound_list[-R :] + bound_list[: -R]
x = x1
y = y1
index = 0
for element in bound_list:
if x == x2 and y == y1:
index+=1
elif x == x2 and y == y2:
index+=1
elif x == x1 and y == y2:
index+=1
arr[x][y] = element
x += dx[index]
y += dy[index]
return min(bound_list)
def solution(rows, columns, queries):
answer = []
arr = [[columns * row + col + 1 for col in range(columns)] for row in range(rows)]
print(arr)
for que in queries:
s_x, s_y, e_x, e_y = que
bound_length = (e_x - s_x + 1) * 2 + (e_y - s_y)
answer.append(rotate(arr, [s_x-1, s_y-1], [e_x-1, e_y-1], 1, bound_length))
return answer
테스트 케이스는 맞았는데 제출 시 3번부터 주루루룩 다 틀린다.
테스트 케이스도 적어서 원인 파악이 안된다....
에서! bound_list에 테두리가 전부 들어가지 않는 오류가 있다는 것을 밝혀냈다!
bound_length의 계산이 틀려서 테두리가 전부 들어가지 않았던 것!
두 번째 풀이
def rotate(arr, TL, BR, R, bound_length):
x1, y1 = TL
x2, y2 = BR
x = x1
y = y1
dx = [0, 1, 0, -1]
dy = [1, 0, -1, 0]
index = 0
bound_list = []
for _ in range(bound_length):
if x == x2 and y == y1:
index+=1
elif x == x2 and y == y2:
index+=1
elif x == x1 and y == y2:
index+=1
bound_list.append(arr[x][y])
x += dx[index]
y += dy[index]
bound_list = bound_list[-R :] + bound_list[: -R]
x = x1
y = y1
index = 0
for element in bound_list:
if x == x2 and y == y1:
index+=1
elif x == x2 and y == y2:
index+=1
elif x == x1 and y == y2:
index+=1
arr[x][y] = element
x += dx[index]
y += dy[index]
return min(bound_list)
def solution(rows, columns, queries):
answer = []
arr = [[columns * row + col + 1 for col in range(columns)] for row in range(rows)]
for que in queries:
s_x, s_y, e_x, e_y = que
bound_length = (e_x - s_x + 1) * 2 + (e_y - s_y + 1) * 2 - 4
answer.append(rotate(arr, [s_x-1, s_y-1], [e_x-1, e_y-1], 1, bound_length))
return answer
문제의 풀이가 이런 꼴인 이유는 백준의 배열 돌리기와 같은 풀이를 공유하고 있어서이다........
시간 복잡도
-
알게 된 점
-
고찰
합집합 계산 방법은 A + B - 교집합........
'알고리즘 > Python' 카테고리의 다른 글
[python] 프로그래머스 - N-Queens (0) | 2022.06.01 |
---|---|
[python] 백준 16926 - 배열 돌리기 1 (0) | 2022.05.16 |
[python] 백준 1932 - 정수 삼각형 (0) | 2022.05.07 |
[python] 백준 1874 - 스택 수열 (0) | 2022.05.07 |
[python] 백준 13305 - 주유소 (0) | 2022.05.04 |