数据结构与算法-BFS 使用场景:层序遍历、最短路径问题(Python)

DFS与BFS

如果只是要遍历树or图的所有结点,DFS和BFS差别不大,非递归写法,DFS借助栈stackBFS借助队列queue
BFS的两个场景:「层序遍历」、「最短路径」

应用一:层次遍历

102. 二叉树的层序遍历(中等)

# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None


class Solution:
    def levelOrder(self, root: TreeNode) -> List[List[int]]:
        if not root:
            return []
        
        res = []
        queue = [root]
        while queue:
            level = []
            l = len(queue)
            for _ in range(l):
                node = queue.pop(0)
                level.append(node.val)
                if node.left:
                    queue.append(node.left)
                if node.right:
                    queue.append(node.right)
            res.append(level)
        return res

返回形如[[3],[1,4]]的结果

应用二:最短路径

最短路径问题也是 BFS 的典型应用,而且其方法与层序遍历关系密切。

Dijkstra 算法解决的是带权最短路径问题;
无权最短路径问题,用 BFS 求解就行了;
在 LeetCode 中,最短路径问题以网格结构为主。

1162. 地图分析(中等)
在这里插入图片描述
方法一:多源BFS
题意理解:
只有一个陆地,从该点出发,寻找离它最远的海洋;
多个陆地,以多个格子同时作为起点,海洋就会被离它最近的陆地先访问到。
即「多源BFS」,把多个源点同时放入初始队列即可

class Solution:
    def maxDistance(self, grid: List[List[int]]) -> int:
        if not grid or not grid[0]:
            return -1
        
        n = len(grid)

        queue = []
        for i in range(n):
            for j in range(n):
                if grid[i][j]==1:
                    queue.append((i,j,0))
        if len(queue)==0 or len(queue)==n*n:
            return -1

        steps = [(1,0),(-1,0),(0,1),(0,-1)]
        while queue:
            i,j,l = queue.pop(0)
            for step in steps:
                x = i+step[0]
                y = j+step[1]
                if x>=0 and x<n and y>=0 and y<n and grid[x][y]==0:
                    grid[x][y]=2
                    queue.append((x,y,l+1))
        return l

方法二:动态规划

相关题目

TODO

层序遍历的一些变种题目

LeetCode 103. Binary Tree Zigzag Level Order Traversal 之字形层序遍历
LeetCode 199. Binary Tree Right Side View 找每一层的最右结点
LeetCode 515. Find Largest Value in Each Tree Row 计算每一层的最大值
LeetCode 637. Average of Levels in Binary Tree 计算每一层的平均值

网格结构中的最短路径

LeetCode 542. 01 Matrix
LeetCode 994. Rotting Oranges 腐烂的橘子(中等)

在真正的图结构中求最短路径

LeetCode 310. Minimum Height Trees

参考资料:
https://leetcode-cn.com/problems/binary-tree-level-order-traversal/solution/bfs-de-shi-yong-chang-jing-zong-jie-ceng-xu-bian-l/

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值