Graphs and traversal
แนะนำใหม่
7:45
โครงสร้างข้อมูลและอัลกอริทึม
This course is about choosing a container by what it costs. The first unit is the yardstick: how cost grows with the size of the input. The next four are the…
บรรยายภาษาอังกฤษ · สลับคำบรรยายภาษาอังกฤษและภาษาจีนได้
ในบทเรียนนี้
| English | ความหมาย |
|---|---|
| adjacency list/əˈdʒeɪsənsi lɪst/ | รายการ adjacency |
| adjacency matrix/əˈdʒeɪsənsi ˈmeɪtrɪks/ | เมทริกซ์ adjacency |
| sparse/spɑːs/ | Describing a graph with few edges compared with the number of vertices, so an adjacency list suits it. |
| Breadth-first search/bredθ fɜːst sɜːtʃ/ | graph search that visits all vertices one edge away, then two edges away, and so on, using a queue |
| Depth-first search/depθ fɜːst sɜːtʃ/ | graph search that follows one path as deep as it can before backing up, using a stack or recursion |
| Dijkstra's algorithm/ˈdeɪkstrəz ˈælɡərɪθəm/ | finds shortest paths from one source in a graph with non-negative edge weights by always settling the nearest unsettled vertex |
| topological sort/ˌtɒpəˈlɒdʒɪkl sɔːt/ | an order of a directed acyclic graph's vertices in which every edge points forwards |
| Kahn's algorithm/kɑːnz ˈælɡərɪθəm/ | A topological sort that repeatedly outputs a node with no incoming edges and removes its outgoing edges. |
List or matrix
- A graph $G = (V, E)$: the course graph has $V = \{A \ldots H\}$ ($8$ nodes) and $10$ undirected edges.
- The adjacency list 邻接表 stores each node's neighbours: $20$ entries for $10$ undirected edges. The adjacency matrix 邻接矩阵 is the $8 \times 8$ grid of $64$ cells, with $1$ where there is an edge.

Ten undirected edges need — adjacency-list entries
ความยาก 1/5 · 100 เหรียญ + บอนัสน้อยๆ เมื่อทำสำเร็จครั้งแรกในวันนี้
Each undirected edge is stored twice, once per endpoint.
Why O(V+E)
- Both traversals mark each node once ($V$ work) and scan each stored edge once ($E$ work): $O(V + E)$ on the course graph. A matrix costs $O(V^2)$, because every row is read across all its columns, edge or not.
- The list wins on sparse 稀疏 graphs ($E \ll V^2$). The matrix wins when the graph is dense or the question is a single cell lookup. Always mark nodes as visited: otherwise any cycle in a real graph makes the search loop for ever.
BFS on an adjacency matrix costs —
ความยาก 1/5 · 100 เหรียญ + บอนัสน้อยๆ เมื่อทำสำเร็จครั้งแรกในวันนี้
Every row reads all V columns, edge or not, so the list is better for sparse graphs.
Two traversals
- Breadth-first search 广度优先搜索 (BFS) from $A$, neighbours in alphabetical order: the layers are $A \,|\, B, C \,|\, D, E \,|\, F, G \,|\, H$, so the order is $A, B, C, D, E, F, G, H$.
- A node's layer is its shortest hop count from $A$, because the queue keeps the frontier in arrival order.
- Depth-first search 深度优先搜索 (DFS) from $A$: $A \to B \to D$; then $D$'s next unvisited neighbour $C$; then $C \to E \to F \to H$; finally $H$'s neighbour $G$.
- The order is $A, B, D, C, E, F, H, G$: deep first, with backtracking. BFS finds shortest hop counts; DFS shows paths and cycles.
BFS from A on the course graph reads —
ความยาก 1/5 · 100 เหรียญ + บอนัสน้อยๆ เมื่อทำสำเร็จครั้งแรกในวันนี้
The queue visits layer by layer: A, then B C, then D E, then F G, then H.
Weighted edges: Dijkstra
- BFS counts hops, not distance. Take the weights $S\text{–}A = 4$, $S\text{–}B = 1$, $B\text{–}A = 2$, $A\text{–}T = 1$, $B\text{–}T = 5$. Dijkstra's algorithm 迪杰斯特拉算法 settles the closest unsettled node each time. The shortest path is $S, B, A, T$, length 4:
| Settle | $d(S)$ | $d(B)$ | $d(A)$ | $d(T)$ |
|---|---|---|---|---|
| $S$ | 0 | 1 | 4 | ∞ |
| $B$ | 0 | 1 | 3 | 6 |
| $A$ | 0 | 1 | 3 | 4 |
| $T$ | 0 | 1 | 3 | 4 |
- Each row settles the smallest unsettled distance (bold) and then lowers its neighbours' distances where the new route is shorter.
- With a min-heap of distances it costs $O((V + E) \log V)$. The greedy choice is safe only with non-negative weights: a negative edge can lower a node that is already settled. Use Bellman–Ford in that case.
In the step's graph, the edge $A\text{–}T$ becomes $3$. What is the shortest distance from $S$ ไป $T$?
ความยาก 2/5 · 140 เหรียญ + บอนัสน้อยๆ เมื่อทำสำเร็จครั้งแรกในวันนี้
A is still 3 via B, so T = min(1 + 5, 3 + 3) = 6: a tie between S, B, T and S, B, A, T.
Dijkstra's algorithm stays correct when one edge has a negative weight.
ความยาก 1/5 · 100 เหรียญ + บอนัสน้อยๆ เมื่อทำสำเร็จครั้งแรกในวันนี้
A settled node could later be reached more cheaply through the negative edge; Bellman-Ford handles that case.
Order a DAG: topological sort
- A directed acyclic graph (DAG) of prerequisites can be listed so that every edge points forward. This is a topological sort 拓扑排序. Kahn's algorithm 卡恩算法 keeps outputting a node with in-degree 0 and deleting its edges.
- For $A \to B$, $A \to C$, $B \to D$, $C \to D$: output $A$, then $B$ and $C$, then $D$. If nodes remain but none has in-degree 0, the graph has a cycle. The cost is $O(V + E)$.
Kahn's algorithm stops with nodes left and none of in-degree 0. This means:
ความยาก 1/5 · 100 เหรียญ + บอนัสน้อยๆ เมื่อทำสำเร็จครั้งแรกในวันนี้
Every node left waits on another: a cycle.
Worked example: where Dijkstra goes wrong
- Directed edges $S \to A = 2$, $S \to B = 4$, $B \to A = -3$. Dijkstra settles $A$ at 2 and then $B$ at 4. The edge $B \to A$ offers 1, but $A$ is already final.
- Bellman–Ford relaxes every edge $V - 1 = 2$ times and finds $d(A) = \mathbf{1}$. If one more pass still improves something, there is a negative cycle. Cost: $O(VE)$.
$S \to A = 2$, $S \to B = 4$, $B \to A = -3$: true shortest distance to $A$?
ความยาก 2/5 · 140 เหรียญ + บอนัสน้อยๆ เมื่อทำสำเร็จครั้งแรกในวันนี้
Via $B$: $4 - 3 = 1$.
Dijkstra's algorithm is correct as long as no cycle has negative total weight.
ความยาก 1/5 · 100 เหรียญ + บอนัสน้อยๆ เมื่อทำสำเร็จครั้งแรกในวันนี้
One negative edge is enough to break it, as here; Bellman–Ford handles negative edges.
Marks that slip away
- Forgetting the visited mark. Any cycle then makes BFS or DFS run for ever.
- BFS for weighted shortest paths. BFS counts hops. In the weighted example the best route $S, B, A, T$ costs $4$ but uses three hops.
- Counting list entries as edges. Each undirected edge is in both endpoints' lists: $10$ edges, $20$ entries.
Recap
- Adjacency list: $O(V + E)$ space, best for sparse graphs; matrix: $V^2$ cells, $O(1)$ edge lookup.
- BFS gives shortest hop counts; DFS shows paths and cycles; both cost $O(V + E)$.
- Dijkstra needs non-negative weights and costs $O((V + E) \log V)$ with a heap.
เกิดปัญหาอะไรขึ้น? เฉพาะทีมเว็บไซต์เท่านั้นที่เห็นข้อมูลนี้