【BFS题型二/迷宫/特殊方向】611 · 骑士的最短路线

这篇博客介绍了一个Python实现的解决方案,用于找到棋盘上两点间的最短路径。算法采用宽度优先搜索(BFS),从起点开始,通过遍历所有可能的相邻格子,直到到达终点。在过程中,它会记录每个位置的距离,最终返回最短路径的长度。如果无法到达目的地,则返回-1。

611 · 骑士的最短路线

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:
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值