题目描述
资源限制
内存限制:256.0MB C/C++时间限制:1.0s Java时间限制:3.0s Python时间限制:5.0s
问题描述
一个8×8的棋盘上有一个马初始位置为(a,b),他想跳到(c,d),问是否可以?如果可以,最少要跳几步?
输入格式
一行四个数字a,b,c,d。
输出格式
如果跳不到,输出-1;否则输出最少跳到的步数。
样例输入
1 1 2 3
样例输出
1
数据规模和约定
0<a,b,c,d≤8且都是整数。
思路分析
只需按要求BFS遍历,7次BFS搜索一定可以搜索到全部格子
关键函数
def knight(coodinate: list) -> list:
x, y = coodinate
p1 = [x - 1, y + 2]
p2 = [x + 1, y + 2]
p3 = [x + 2, y + 1]
p4 = [x + 2, y - 1]
p5 = [x + 1, y - 2]
p6 = [x - 1, y - 2]
p7 = [x - 2, y - 1]
p8 = [x - 2, y + 1]
coods = [p1, p2, p3, p4, p5, p6, p7, p8]
coods_copy = coods.copy()
for p in coods_copy:
x, y = p
if (x < 0 or y < 0) or (x > 7 or y > 7):
coods.remove(p)
return coods
def update_chessboard(cood: list, step: int) -> list:
global chessboard
knight_places = knight(cood)
for p in knight_places:
x, y = p
chessboard[y][x] = min(chessboard[y][x], step)
return knight_places
def kps(li: list, step) -> list:
kps_ = []
for co in li:
kps_.extend(update_chessboard(cood=co, step=step))
return kps_
def sort_path(cood_1: list, cood_2: list) -> int:
global chessboard
kp = [cood_1]
x1, y1 = cood_1
x2, y2 = cood_2
chessboard[y1][x1] = 0
step = 1
while step <= 7:
kp = kps(kp, step=step)
step += 1
if chessboard[y2][x2] < 100:
return chessboard[y2][x2]
else:
return -1
完整代码
# 问题描述
# 一个8×8的棋盘上有一个马初始位置为(a,b),他想跳到(c,d),问是否可以?如果可以,最少要跳几步?
# 输入格式
# 一行四个数字a,b,c,d。
# 输出格式
# 如果跳不到,输出-1;否则输出最少跳到的步数。
chessboard = [[100] * 8 for _ in range(8)]
def knight(coodinate: list) -> list:
x, y = coodinate
p1 = [x - 1, y + 2]
p2 = [x + 1, y + 2]
p3 = [x + 2, y + 1]
p4 = [x + 2, y - 1]
p5 = [x + 1, y - 2]
p6 = [x - 1, y - 2]
p7 = [x - 2, y - 1]
p8 = [x - 2, y + 1]
coods = [p1, p2, p3, p4, p5, p6, p7, p8]
coods_copy = coods.copy()
for p in coods_copy:
x, y = p
if (x < 0 or y < 0) or (x > 7 or y > 7):
coods.remove(p)
return coods
def update_chessboard(cood: list, step: int) -> list:
global chessboard
knight_places = knight(cood)
for p in knight_places:
x, y = p
chessboard[y][x] = min(chessboard[y][x], step)
return knight_places
def kps(li: list, step) -> list:
kps_ = []
for co in li:
kps_.extend(update_chessboard(cood=co, step=step))
return kps_
def sort_path(cood_1: list, cood_2: list) -> int:
global chessboard
kp = [cood_1]
x1, y1 = cood_1
x2, y2 = cood_2
chessboard[y1][x1] = 0
step = 1
while step <= 7:
kp = kps(kp, step=step)
step += 1
if chessboard[y2][x2] < 100:
return chessboard[y2][x2]
else:
return -1
def main():
a, b, c, d = list(map(int, input().rstrip().split()))
print(sort_path([a - 1, b - 1], [c - 1, d - 1]))
if __name__ == "__main__":
main()
运行结果
请读者合理引用,转载文章内容,部分内容参考自网络,如有侵权联系删除