Graph search的应用广泛:可以检查网络是否相互连接,找两点最短路线等等
1. Generic Graph Search:
目的:找到start vertex的每个可寻点,每个点直走一次
Generic Algorithm:(已知graph G,Vetex s)
1. 初始S为explored,其他为unexplored
2. while loop,选择edge(u,v), u explored, v unexplored
标记v explored
引出两种search方式:
BFS和DFS
简介: BFS(Breadth -First Search) :
--------explored nodes in layers
--------can compute shortest path
--------can compute connected components of an undirected graph
Note: O(m+n)时间,用FIFO存储
DFS(Depth-First Search): (看起来很二)
-----------explore aggressively like a maze,backtrack when necessary
-----------compute topological ordering of a directed acyclic graph
-----------compute connected components in directed graphs
2. BFS
BFS的算法:
-------Mark S as explored
-------let Q = queue data structure (FIFO) initialized with s
-------while Q 不是空
--------remove the first node of Q, call it V
--------for each edge(v,w)
O(1) 时间[ -----if w unexplored
-----mark w as explored
------add w to Q (at the end)]
应用:1. 最短距离:compute dist(v), the fewest# of edges on path from s to v
在BFS基础上加上代码: initialize dist(v) = 0 if v = s
= infinity if v 不为s
when considering edge(V,W)
if w unexplored, then set dist(w) = dist(v)+1;
这样在终止处,dist(v) = i, v in ith layer, s-v最短的path就是有i个edges
2. undirected connectivity:
connected components vis BFS:
附加的代码就是 ------initialize all nodes as unexplored 时间[O(n)]
(assume labelled 1 to n)
------for i=1 to n 时间O(n)
------if i not yet explored <in some previous BFS>(时间O(n))
-----BFS(G,i) <discovers precisely i's connected component>
运行时间:O(m+n) m 为O(1)per node, O(1)per edge in each BFS
3.DFS
运行时间同样是O(m+n)
代码:和BFS类似,但是用的是stack不是queue
recursive version: ---DFS( graph G, start vertex s)
---mark s as explored
---- for every edge(s,v)
----if v unexplored
-----DFS(G,V)
它是一个不断探索,回巡的过程。运行的时间同样是线性的O(m+n)
其中n=#of nodes reachable from s
m=#of edges reachable from s
看起来很笨拙,但是对于topological sort很好用
4. Topological sort via DFS
定义:A topological ordering of a directed graph G is a labeling f of G's nodes such that:
1. the f(v)'s are the set {1,2....n}
2. (u,v) 属于G = > f(u)<f(v)
topological就是会有相应的顺序限制,并且如果G存在一个cycle,那么就不再是topological ordering了
没有directed cycle的话,可以compute topological ordering in O(m+n)时间
这样问题的直接解决方式:
-----let v be a sink vertex of G
-----set f(v)=n
-----recurse on G-{v};
所需要的时间仍然是O(m+n),原因和上面相同
正确性分析:
需要知道(u,v) 如果是edge,那么f(u)<f(v)
情形1:u visited by DFS before v, ------>recursive call corresponding to v finishes before that of u---->f(v)>f(u)
情形2:v visited by DFS before u --------->v's recursive call finishes before u's even starts--------------->f(v)>f(u)