图——广度优先搜索(Graph

来源:互联网 发布:淘宝客怎样设置佣金 编辑:程序博客网 时间:2024/05/13 21:09

简介(Introduction)
Breadth-first search(BFS) visits all nodes in alphabetical order that are one step away from start node, then all nodes that are two steps away from start node, and so on.
这里写图片描述
DFS order: a, b, c, d, e, f, g.

检索队列(The Traversal Queue)
We can use a queue to track where we are in overall process. For above graph,
这里写图片描述
Inject queue order: a, b, c, d, e, f, g.
Eject queue order: a, b, c, d, e, f, g.
We visit a node, eject it and then inject its unvisited nodes. Do these operations repeatedly until the queue becomes empty.

搜索树(BFS Tree)
We can use a BFS tree to represent traversal process.
这里写图片描述

算法伪代码(Algorithm Pseudocode)

function DFS(<V, E>)    mark each node in V with 0    count ⟵ 0    init(Queue)    for each node v in V do        if v is marked 0 then             count ⟵ count + 1             mark v with count             inject(Queue, v)             while Queue is non-empty do                 u ⟵ eject(Queue)                 for each edge (u, w) do                     if w is marked 0 then                         count ⟵ count + 1                         mark w with count                         inject(Queue, w)

时间复杂度(Time Complexity)
The complexity of BFS is the same with DFS.
For using adjacency matrix, Θ(|V|^2).
For using adjacency list, Θ(|V| + |E|).

写在最后的话(PS)
Ask yourself, what problems in practical can we solve by using BFS?
Welcome questions always and forever.

原创粉丝点击