Q. 체스판 위에 한 나이트가 놓여져 있다. 나이트가 한 번에 이동할 수 있는 칸은 아래 그림에 나와있다. 나이트가 이동하려고 하는 칸이 주어진다. 나이트는 몇 번 움직이면 이 칸으로 이동할 수 있을까?
A. 정답코드
def moving(l, start, end):
visited = [[False] * l for _ in range(l)]
moves = [(2, 1), (2, -1), (-2, 1), (-2, -1), (1, 2), (1, -2), (-1, 2), (-1, -2)]
queue = [(start[0], start[1], 0)]
visited[start[0]][start[1]] = True
while queue:
x, y, current_moves = queue.pop(0)
if (x, y) == end:
return current_moves
for move in moves:
new_x, new_y = x + move[0], y + move[1]
if 0 <= new_x < l and 0 <= new_y < l and not visited[new_x][new_y]:
queue.append((new_x, new_y, current_moves + 1))
visited[new_x][new_y] = True
return
number = int(input())
for _ in range(number):
l = int(input())
start = tuple(map(int, input().split()))
end = tuple(map(int, input().split()))
result = moving(l, start, end)
print(result)
움직이는 함수를 생성하여 bfs형식으로 queue를 구현하고 탐색하는 기법을 사용했습니다.
'Python > codingTest' 카테고리의 다른 글
[leetCode #704] Binary Search (0) | 2024.01.13 |
---|---|
[Python CT#5] 최대 힙 (1) | 2024.01.08 |
[Python CT#4] 배열요소로 큰 수 만들기 (0) | 2024.01.06 |
[Python CT#3] K번째 큰 요소 (0) | 2024.01.06 |
[Python CT#1] 그룹 애너그램 (0) | 2024.01.05 |