Give the adjacent matrix of an undirected graph G as follows: where 0 indicates that there is no corresponding edge, and the non-zero values indicate the costs of the corresponding edges.
\(\begin{matrix}&A&B&C&D&E&F&G&H\\A&0&3&4&0&5&0&2&0\\B&3&0&1&2&0&2&0&3\\C&4&1&0&0&5&3&0&0\\D&0&2&0&0&0&0&0&5\\E&5&0&5&0&0&0&4&0\\F&0&2&3&0&0&0&2&6\\G&2&0&0&0&4&2&0&0\\H&0&3&0&5&0&6&0&0\end{matrix}\)
(a) Please perform depth-first search (DFS), starting at vertex A. Assume the visiting order of the adjacent nodes are in lexicographic order, e.g., when exploring the adjacent nodes of vertex A, consider A-B before A-C or A-E. Please write the list of vertices in the order that they are visited by DFS and BFS, respectively. (2 分) (b) Please perform breadth-first search (BFS), starting at vertex A. (2 分) (c) Give one situation that you would need to perform BFS instead of DFS. (2 分) (d) Give one situation that you would need to perform DFS instead of BFS. (2 分) (e) Please explain Kruskal's algorithm and find the minimum-cost spanning tree of the graph G. (4 分) (f) How many articulation points are in the graph G? Please explain your answer. (3 分)
由矩陣讀出邊(無向):\(AB\,3,\ AC\,4,\ AE\,5,\ AG\,2,\ BC\,1,\ BD\,2,\ BF\,2,\ BH\,3,\ CE\,5,\ CF\,3,\ DH\,5,\ EG\,4,\ FG\,2,\ FH\,6\)(14 條)
鄰居(字母序):A:B C E G;B:A C D F H;C:A B E F;D:B H;E:A C G;F:B C G H;G:A E F;H:B D F
(a) DFS:A → B(A 的第一個)→ C(B 的鄰居 A 已訪、C 未訪)→ E(C:A、B 已訪,E 未訪)→ G(E:A、C 已訪)→ F(G:A、E 已訪)→ H(F:B、C、G 已訪,H 未訪)→ D(H:B 已訪、D 未訪)→ D 的鄰居都已訪,一路退回
DFS:A, B, C, E, G, F, H, D
(b) BFS(queue):A 出列,把 B C E G 入列;B 出列,新鄰居 D F H 入列;C、E、G、D、F、H 出列時沒有新的點
BFS:A, B, C, E, G, D, F, H
(c) 要找「經過最少邊數」的路徑(unweighted graph 的 shortest path)、或一層一層往外找離起點最近的點時用 BFS。例:社群網站找「朋友的朋友」(距離 2 以內)、網路爬蟲依層級爬、迷宮最短步數;DFS 不保證先找到的是最短路徑
(d) 要走到底再回頭、需要完整的路徑與回溯、或記憶體吃緊時用 DFS(stack 深度只要路徑長度,BFS 的 queue 要放一整層)。例:偵測 cycle、topological sort、找 connected/strongly connected components、找 articulation point、走迷宮/backtracking 窮舉所有路徑
(e) Kruskal:把所有邊依權重由小到大排序,依序檢查每條邊;若兩端點在不同的連通元件(用 union-find 判斷),就加入並合併兩個元件,否則(會形成 cycle)跳過;選滿 \(|V|-1=7\) 條邊就停
選到第 7 條(EG)時 8 個點全部連起來,後面的 AE 5、CE 5、DH 5、FH 6 不用再看
MST 邊:BC, AG, BD, BF, FG, BH, EG;總成本 \(1+2+2+2+2+3+4=16\)
這棵 MST 唯一:權重 2 的四條邊(AG、BD、BF、FG)加上 BC 不構成 cycle,D、H、E 各自只有一條最輕的連接邊(BD、BH、EG)
(f) articulation point:拿掉它之後圖不再連通的點。逐點檢查:拿掉任一點後,剩下的點仍連通——例如拿掉 B,D 還能經 H–F 連回去;拿掉 F,H 還有 B、D;拿掉 A,E 還有 C、G;其餘點的鄰居彼此另有路徑可通。用 DFS(A, B, C, E, G, F, H, D)的 low-link 也可以確認:沒有任何點有 child 的 low 值 ≥ 它自己的 discovery time(根 A 的 DFS 樹只有一個 child B)
0 個(G 是 biconnected graph)