from typing import (
List,
)
from lintcode import (
Point,
)
"""
Definition for a point:
class Point:
def __init__(self, x=0, y=0):
self.x = x
self.y = y
"""
class Solution:
"""
@param grid: a chessboard included 0 (false) and 1 (true)
@param source: a point
@param destination: a point
@return: the shortest path
"""
def shortest_path(self, grid: List[List[bool]], source: Point, destination: Point) -> int:
# write your code here
from collections import deque
n,m=len(grid),len(grid[0])
xs,ys=source.x,source.y
offset=[(1,2),(1,-2),(-1,2),(-1,-2),(2,1),(2,-1),(-2,1),(-2,-1)]
xg,yg=destination.x,destination.y
def bfs(xs,ys,xg,yg):
queue=deque([(xs,ys)])
distance={(xs,ys):0}
while queue:
【BFS题型二/迷宫/特殊方向】611 · 骑士的最短路线
于 2022-05-02 23:00:50 首次发布
这篇博客介绍了一个Python实现的解决方案,用于找到棋盘上两点间的最短路径。算法采用宽度优先搜索(BFS),从起点开始,通过遍历所有可能的相邻格子,直到到达终点。在过程中,它会记录每个位置的距离,最终返回最短路径的长度。如果无法到达目的地,则返回-1。

最低0.47元/天 解锁文章

被折叠的 条评论
为什么被折叠?



