티스토리 뷰

728x90

https://www.acmicpc.net/problem/7562

 

7562번: 나이트의 이동

체스판 위에 한 나이트가 놓여져 있다. 나이트가 한 번에 이동할 수 있는 칸은 아래 그림에 나와있다. 나이트가 이동하려고 하는 칸이 주어진다. 나이트는 몇 번 움직이면 이 칸으로 이동할 수

www.acmicpc.net

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
def bfs(x, y):
    queue = [[x, y]]
    check[x][y] = True
    direction = [(12), (21), (2-1), (1-2), (-1-2), (-2-1), (-21), (-12)]
    while queue:
        x, y = queue[0][0], queue[0][1]
        del queue[0]
        if x == end_x and y == end_y:
            return chess[x][y]
        for dx, dy in direction:
            nx, ny = x + dx, y + dy
            if 0 <= nx < i and 0 <= ny < i and not check[nx][ny]:
                queue.append((nx, ny))
                check[nx][ny] = True
                chess[nx][ny] = chess[x][y] + 1
 
 
for _ in range(int(input())):
    i = int(input())  # 체스판 한 변 길이
    check = [[False* i for _ in range(i)]
    chess = [[0* i for _ in range(i)]
    start_x, start_y = map(int, input().split())
    end_x, end_y = map(int, input().split())
    print(bfs(start_x, start_y))
cs

 

댓글