跳马
问题描述
一个8×8的棋盘上有一个马初始位置为(a,b),他想跳到(c,d),问是否可以?如果可以,最少要跳几步?
输入格式
一行四个数字a,b,c,d。
输出格式
如果跳不到,输出-1;否则输出最少跳到的步数。
样例输入
1 1 2 3
样例输出
1
思路
- 使用广搜,不断往外走然后记录步数,标记访问过的点即可。
代码
a, b, c, d = map(int, input().split(' '))
step = [(1, 2), (1, -2), (-1, 2), (-1, -2), (2, 1), (2, -1), (-2, 1), (-2, -1)]
visit = [[False]*8 for _ in range(8)]
queue = [(a, b, 0)] # 坐标、步数
while queue:
y, x, t = queue.pop(0)
if y == c and x == d:
print(t)
break
for dy, dx in step:
ny = y + dy
nx = x + dx
if -1 < ny < 8 and -1 < nx < 8 and not visit[ny][nx]:
queue.append((ny, nx, t+1))
visit[ny][nx] = True
if not queue:
print(-1)