본문 바로가기

프로그래밍

[백준 7562 파이썬] 나이트 이동

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# 7562 나이트 이동
# BFS
# Pypy3 752ms
 
 
dx = [-2-112-2-11 ,2]
dy = [-1-2-2-1,1221]
 
def bfs(start, end):
    queue = [start]
    board[start[0]][start[1]]=1
 
    while queue:
 
        pos = queue.pop(0)
        if end[0]==pos[0and end[1]==pos[1]:
            return board[pos[0]][pos[1]]-1
 
        for i in range(8):
            nx = pos[0+dx[i]
            ny = pos[1+dy[i]
            if 0<=nx <and 0<=ny<L:
                if board[nx][ny]==0:
                    queue.append((nx, ny))
                    board[nx][ny]= board[pos[0]][pos[1]]+1
 
 
 
 
 
= int(input())
for i in range(T):
    L = int(input())
    x1, y1 = map(int, input().split())
    x2, y2 = map(int, input().split())
    board = [[0]*for _ in range(L)]
    if x1==x2 and y1==y2:
        print(0)
    else:
        print(bfs((x1,y1), (x2,y2)))