Bfs Lemmas & Dfs
Bfs Lemmas & Dfs
• δ(s,v) = 起點 s 到 v 點的最短距離
• v.d = d [v] = distance from the starting point s to the v point (= number of
sides = path length)
• u = v.π (when white v is found starting from point u, meaning u is the previous
one of v)
Lemma 22.1
Let s in V be an arbitrary vertex. Then, for any edge (u,v) in E, δ(s,v)
≤δ(s,u)+1
Proof
Case1. If u is reachable from s, then so is v. In this case, the
u shortest path from s to v cannot be longer than the shortest
path from s to u followed by the edge
Proof:
suppose v is white when we scan u, then
d[v]=d[u]+1≥δ(s,u)+1≥δ(s,v)
by alg, induction hypothesis, and Lemma 22.1
d[I]=∞ δ(A,I) = 3
Lemma 22.3
Suppose during the execution of BFS, the queue Q contains [v1,v2,…,vr], where v1 is the he
ad and vr is the tail of Q. Then, d[vr]≤d[v1]+1, and d[vi]≤d[vi+1] for i=1,2,…,r-1
Queue: v1 v2 v3 v4 v5 v6
C D E F G H
1 1 2 2 2 2
2 = d[v6] ≤ d[v1]+1=1+1=2
1 = d[v2] ≤ d[v2+1] = 2
…
DEPTH-FIRST SEARCH (DFS)
深度優先搜尋法,是一種用來遍尋一個樹 (tree) 或圖 (graph) 的演算法。由圖的某
一點當成根來開始探尋,先探尋邊 (edge) 上未搜尋的一節點 (vertex or node) ,並
儘可能深的搜索,直到該節點的所有邊上節點都已探尋;就回溯 (backtracking) 到
前一個節點,重覆探尋未搜尋的節點,直到找到目的節點或遍尋全部節點。
Depth-first search is an algorithm used to traverse a tree or graph. Start searching at a
point in the graph as a root. First search for a node (vertex or node) on the edge that is
not searched, and search as deep as possible until all nodes on the edge of the node
have been searched; then backtrack (backtracking) Go to the previous node and
repeatedly search the unsearched nodes until you find the destination node or search all
nodes.
Example:
假設起始點為 A ,且每一節點由左至右的順序來搜尋下個節點,則結果為 : A, B, E, F, D, C,
G,
生成的 DFS tree 如右圖
實現方法
1. 訪問頂點 v ;
2. 依次從 v 的未被訪問的鄰接點出發,對圖進行 DFS ;直
至圖中和 v 有路徑相通的頂點都被訪問;
3. 若此時圖中尚有頂點未被訪問,則從一個未被訪問的頂
點出發,重新進行 DFS ,直到圖中所有頂點均被訪問過為
止
Visit vertex v;
Starting from the unvisited adjacencies of v in turn, DFS the
graph; until the vertices in the graph that have paths connected
to v are visited;
If there are vertices in the graph that have not been visited at
backtracking ( 回朔 )
this time, starting from an unvisited vertex, DFS is performed
again until all vertices in the graph have been visited.
Example
By DFS: 1,2,6,4,5,3,7