ZXAlgorithm - C4 BFS

Outline
BFS in Binary tree
BFS in Graph
BFS on Matrix
Topological Sorting


0 什么时候使用BFS

图的遍历,最短路径,非递归找所有方案

1 BFS in Binary tree

2 BFS in Graph

3 BFS in Matrix

矩阵和图的对比:

4 Topological sorting

四种问法:
求任意1个拓扑排序(Topological Order)
问是否存在拓扑排序(是否可以被拓扑排序)
求所有的拓扑排序(DFS)
求是否存在且仅存在一个拓扑排序 (Queue中最多同时只有1个节点)

5 Experience

  • 能用 BFS 的一定不要用 DFS(除非面试官特别要求)
  • BFS 的两个使用条件
    • 图的遍历(由点及面,层级遍历)
    • 简单图最短路径
  • 是否需要层级遍历
    • size = queue.size()
  • 拓扑排序必须掌握!
  • 坐标变换数组
    • deltaX, deltaY
    • inBound

6 Template总结

1 Level order traversal

While(?queue.empty)
{Size = queue.size
For(i 0-size){}
} queue use queue and resultlist use poll and offer

2 Just BFS

For(i 0-size) queue use list get and add method

3 Use while

While(?queue.isEmpty()) { queue.poll(); loop(queue.offer());
}
Conclusion: 1 cost more time 2 cost more space, use 3 best(不使用index)
简单来说就是队列结构,但是可以有2个队列(层次遍历),或者1个队列,用for或者while来遍历

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容