Kodewick
開始學 →
題型與套路:圖36 / 52

題型與套路:圖

第 36 課,共 52 課 · 第 6 部分 · 圖 · 約 18 分鐘

這一課複習圖的題的三個套路:網格就是圖,每格一個頂點,用 vector<string> 存、方向陣列找鄰居;最短路先看邊權再選演算法;考試手算題按固定的表來填。

圖的題,難點常常不在演算法本身,而在於看出它是一張圖,再選對工具。一張地圖、一個迷宮、一個棋盤、一份依賴關係表,背後都是頂點和邊。這一課按題型分關:網格、選最短路演算法、408 手算、度和邊數的公式,每關一個套路。

套路一:網格就是一張圖

二維網格裡,每個格子是一個頂點,和上下左右(有時還有斜著的)格子之間有邊。邊不用存:網格用 vector<string> 或 vector<vector<int>> 存,鄰居用兩個方向陣列 dr、dc 現算。

  • 數連通塊(島嶼數量、影像裡的連通區域):逐格掃,遇到沒訪問過的陸地,塊數加 1,從它 DFS,把整塊「淹掉」。這叫洪水填充(flood fill)。
  • 最少步數(迷宮、騎士走幾步):BFS,佇列是 queue<pair<int, int>>。
  • 從好幾個起點同時擴散(火勢蔓延、離最近的出口多遠):把所有起點一起放進佇列,再 BFS,叫多源 BFS。
01234011001110011200100310110

島嶼數量:1 是陸地,0 是水,上下左右相連的陸地是一個島。逐格掃,遇到陸地就 DFS 把整個島標出來(圖裡用字母標是第幾個島,程式碼裡直接改成 0)
main.cpp
1#include <iostream>2#include <vector>3#include <string>4using namespace std;5 6// 淹掉 (r, c) 所在的島,返回它有幾格;g 按引用傳,改的是原來的網格7int sink(vector<string>& g, int r, int c) {8    if (r < 0 || r >= (int)g.size() || c < 0 || c >= (int)g[0].size() || g[r][c] != '1')9        return 0;10    g[r][c] = '0';                               // 改成水,就不會再來11    return 1 + sink(g, r + 1, c) + sink(g, r - 1, c) + sink(g, r, c + 1) + sink(g, r, c - 1);12}13 14int main() {15    vector<string> g = {16        "11001",17        "10011",18        "00100",19        "10110",20    };21    int count = 0;22    for (int r = 0; r < (int)g.size(); r++)23        for (int c = 0; c < (int)g[0].size(); c++)24            if (g[r][c] == '1') {25                count++;26                int cells = sink(g, r, c);27                cout << "第 " << count << " 個島從 (" << r << ", " << c << ") 開始," << cells << " 格\n";28            }29    cout << "一共 " << count << " 個島\n";30    return 0;31}
輸出
第 1 個島從 (0, 0) 開始,3 格
第 2 個島從 (0, 4) 開始,3 格
第 3 個島從 (2, 2) 開始,3 格
第 4 個島從 (3, 0) 開始,1 格
一共 4 個島

先判斷出界和「是不是沒訪問過的陸地」,再遞迴:這樣四個方向的呼叫都不用各自檢查。直接把陸地改成 '0' 當作「訪問過」,省掉一個 visited 陣列(題目不讓改輸入時,再開一個 vector<vector<bool>>)。g 一定要按引用傳:寫成 vector<string> g,每次遞迴都會複製整張網格,改的也是副本。g.size() 是無符號的 size_t,和可能是 −1 的 r 比較前先轉成 int。

單選

1 是陸地、0 是水。只算上下左右相連,這個網格有幾個島?

11 0 120 1 031 0 1
練習 1

島嶼數量

補全 sink:出界、或者不是陸地(g[r][c] != '1')就返回;否則把它改成 '0',再往四個方向遞迴。

要顯示
4
exercise1.cpp
1#include <iostream>2#include <vector>3#include <string>4using namespace std;5 6void sink(vector<string>& g, int r, int c) {7    // 出界或不是 '1' 就 return;否則 g[r][c] = '0',再 sink 上下左右8}9 10int main() {11    vector<string> g = {12        "110010",13        "100011",14        "001000",15        "011001",16        "000011",17    };18    int count = 0;19    for (int r = 0; r < (int)g.size(); r++)20        for (int c = 0; c < (int)g[0].size(); c++)21            if (g[r][c] == '1') {22                count++;23                sink(g, r, c);24            }25    cout << count << "\n";26    return 0;27}
輸出
點「執行」或按 Ctrl+Enter
練習 2

腐爛的橘子

2 是爛橘子,1 是好橘子,0 是空格。每過一分鐘,爛橘子會讓上下左右的好橘子變爛。多源 BFS:所有爛橘子一開始一起入隊(時間 0)。補全 BFS 裡看四個方向的部分;有好橘子永遠爛不到時返回 -1。

要顯示
6
-1
exercise2.cpp
1#include <iostream>2#include <vector>3#include <queue>4#include <utility>5using namespace std;6 7int minutes(const vector<vector<int>>& g) {8    int R = g.size(), C = g[0].size();9    vector<vector<int>> t(R, vector<int>(C, -1));10    queue<pair<int, int>> q;11    int dr[4] = {1, -1, 0, 0}, dc[4] = {0, 0, 1, -1};12    for (int r = 0; r < R; r++)13        for (int c = 0; c < C; c++)14            if (g[r][c] == 2) {15                t[r][c] = 0;16                q.push({r, c});17            }18    while (!q.empty()) {19        int r = q.front().first, c = q.front().second;20        q.pop();21        // 四個方向:不出界、是好橘子(1)、t 還是 -1,就 t = t[r][c] + 1,入隊22    }23    int most = 0;24    for (int r = 0; r < R; r++)25        for (int c = 0; c < C; c++) {26            if (g[r][c] == 1 && t[r][c] == -1) return -1;27            if (t[r][c] > most) most = t[r][c];28        }29    return most;30}31 32int main() {33    vector<vector<int>> a = {{2, 1, 1, 0}, {1, 1, 0, 1}, {0, 1, 1, 1}, {0, 0, 0, 1}};34    vector<vector<int>> b = {{2, 1, 1, 0}, {1, 1, 0, 1}, {0, 1, 1, 1}, {1, 0, 0, 1}};35    cout << minutes(a) << "\n" << minutes(b) << "\n";36    return 0;37}
輸出
點「執行」或按 Ctrl+Enter

套路二:最短路,先看邊權

題目的樣子用什麼時間
沒有權,或者每條邊一樣長(走幾步、換乘幾次)BFS,queueO(n + e)
邊權只有 0 和 10-1 BFS:deque,0 的邊 push_front,1 的邊 push_backO(n + e)
一個起點,邊權都 ≥ 0Dijkstra(n 小用陣列,圖稀疏用 priority_queue)O(n²) 或 O((n + e) log n)
一個起點,有負權邊Bellman-Ford / SPFAO(n·e)
有向無環圖按拓撲序鬆弛一遍O(n + e)
所有點兩兩之間,n 只有幾百FloydO(n³)

幾個容易錯的地方:

  • 有負權邊還用 Dijkstra:Dijkstra 那一課的反例,結果會錯。
  • 用 BFS 求帶權圖的最短路:邊數少的路不一定短。
  • priority_queue 忘了寫 greater:預設是大頂堆,每次彈出的是最遠的。
  • Floyd 的三層迴圈把 k 放在裡面:d[i][j] = min(d[i][j], d[i][k] + d[k][j]) 的 k 必須在最外層。它的意思是「只允許經過 0~k 當中轉站時的最短路」,要先把 k − 1 的情況算完整。
  • INF 取 INT_MAX:INF + w 溢位成負數。取 10 億,兩個相加也不超過 int。
  • 無向圖用 Bellman-Ford,一條負權邊就等於一個負權環(來回走一趟就變短)。
單選

有向無環圖,有幾條邊的權是負數,求一個起點到所有頂點的最短路,要 O(n + e)。用什麼?

練習 3

Floyd:所有點對的最短路

補全 Floyd 的三層迴圈:k 在最外層,d[i][k] + d[k][j] 更小就更新 d[i][j]。(INF 取 10 億,兩個 INF 相加也不會溢位 int。)

要顯示
0 5 8 9 
6 0 3 4 
3 5 0 1 
2 4 7 0 
exercise3.cpp
1#include <iostream>2#include <vector>3using namespace std;4 5const int INF = 1000000000;6 7int main() {8    int n = 4;9    vector<vector<int>> d(n, vector<int>(n, INF));10    for (int i = 0; i < n; i++) d[i][i] = 0;11    d[0][1] = 5; d[0][3] = 10; d[1][2] = 3;12    d[2][3] = 1; d[3][0] = 2; d[3][1] = 4;      // 有向邊13    // for k,for i,for j:d[i][k] + d[k][j] < d[i][j] 就更新14    for (int i = 0; i < n; i++) {15        for (int j = 0; j < n; j++)16            cout << d[i][j] << " ";17        cout << "\n";18    }19    return 0;20}
輸出
點「執行」或按 Ctrl+Enter

套路三:408 的手算題

考研的圖論大題基本是「按演算法一步步寫出過程」。幾個固定的格式:

Dijkstra 填表:每一輪一行,寫出所有沒定下的頂點當前的 dist,圈出最小的那個(這一輪定下它),下一行用它鬆弛。用 Dijkstra 那一課的圖(0–1:7、0–2:2、2–1:3、1–3:4、2–4:9、3–4:1、3–5:6、4–5:3),從 0 出發:

12345定下第 1 輪      第 2 輪      第 3 輪      第 4 輪      第 5 輪      

Dijkstra 的手算表:每行是一輪,高亮的是這一輪定下的頂點;定下以後它那一列寫「–」

Prim 和 Kruskal 的順序:Prim 寫「從 v 開始,依次加入的邊」,每一步從「一頭在樹上、一頭不在」的邊裡挑最短的;Kruskal 寫「按權從小到大,選、跳過、選……」,跳過的要說明它會和哪幾條邊成環。

所有拓撲序列:每一步把當前入度為 0 的頂點每個都試一次,畫成一棵樹,葉子數就是序列個數。這個程式用回溯把它們全列出來:

main.cpp
1#include <iostream>2#include <vector>3using namespace std;4 5int n = 5, total = 0;6vector<vector<int>> adj(n);7vector<int> indeg(n, 0), order;8vector<bool> used(n, false);9 10void all() {11    if ((int)order.size() == n) {12        total++;13        for (int v : order) cout << v << " ";14        cout << "\n";15        return;16    }17    for (int v = 0; v < n; v++)18        if (!used[v] && indeg[v] == 0) {         // 每個入度為 0 的都試一次19            used[v] = true;20            order.push_back(v);21            for (int x : adj[v]) indeg[x]--;22            all();23            for (int x : adj[v]) indeg[x]++;     // 撤銷,試下一個24            order.pop_back();25            used[v] = false;26        }27}28 29int main() {30    auto add = [](int u, int v) { adj[u].push_back(v); indeg[v]++; };31    add(0, 2); add(1, 2); add(2, 3); add(2, 4);  // 0、1 都在 2 前面,2 在 3、4 前面32    all();33    cout << "一共 " << total << " 個\n";34    return 0;35}
輸出
0 1 2 3 4 
0 1 2 4 3 
1 0 2 3 4 
1 0 2 4 3 
一共 4 個
單選

有向邊 A → B、A → C、A → D、B → E。一共有幾個拓撲序列?

套路四:度和邊數的公式

408 的選擇題愛考幾個和度、邊數有關的公式。每一條背後都是一個簡單的數數道理,比如每條邊有兩頭,所以無向圖所有頂點的度加起來是 2e。

題目問答案
無向圖所有頂點的度之和2e
有向圖入度之和、出度之和都是 e
n 個頂點的無向完全圖有幾條邊n(n − 1) / 2(有向完全圖 n(n − 1))
n 個頂點的連通圖至少幾條邊n − 1(就是一棵生成樹)
n 個頂點,至少幾條邊才能保證一定連通(n − 1)(n − 2) / 2 + 1
鄰接矩陣中 1 的個數無向圖 2e,有向圖 e
鄰接表中邊結點的個數(vector<vector<int>> 裡元素的總數)無向圖 2e,有向圖 e
n 個頂點、e 條邊的森林有幾棵樹n − e

「保證連通」那一條的想法:先讓 n − 1 個頂點兩兩全連上,用掉 (n − 1)(n − 2) / 2 條邊,最後一個頂點還是孤零零的;再多一條就一定連上它。

單選

7 個頂點的無向圖(沒有重邊),至少要幾條邊,才能保證它不管怎麼連都是連通的?

單選

一個無向圖有 10 條邊,所有頂點的度加起來是多少?它的鄰接矩陣裡有幾個 1?

小結

這一課帶走

圖的三個套路

  • 網格就是圖:方向陣列現算鄰居;數塊用 DFS 淹掉,最少步數用 BFS
  • 多個起點一起擴散:全部先放進 queue,再 BFS
  • 最短路先看邊權:無權 BFS,0/1 用 deque,非負 Dijkstra,負權 Bellman-Ford,所有點對 Floyd
  • 408:Dijkstra 每輪定一個填表;度之和 2e;保證連通 (n − 1)(n − 2) / 2 + 1
1int dr[4] = {1, -1, 0, 0}, dc[4] = {0, 0, 1, -1};2for (int k = 0; k < 4; k++) {3    int nr = r + dr[k], nc = c + dc[k];4    if (nr >= 0 && nr < R && nc >= 0 && nc < C && …) q.push({nr, nc});5}

第 5 章快刷

5 道題:同一個鄰接表上的 BFS 和 DFS、Kahn 排出的順序、priority_queue 版 Dijkstra 的距離、Kruskal 的總權。先自己算出印出什麼,再點選項。

猜輸出猜錯也沒關係

鄰接表,鄰居按加邊的順序排。從 0 出發做 BFS,印出什麼?

1#include <iostream>2#include <vector>3#include <queue>4using namespace std;5 6int main() {7    int n = 6;8    vector<vector<int>> adj(n);9    auto add = [&](int u, int v) { adj[u].push_back(v); adj[v].push_back(u); };10    add(0, 3); add(0, 1); add(1, 4); add(3, 4); add(3, 2); add(4, 5); add(2, 5);11    vector<bool> seen(n, false);12    queue<int> q;13    seen[0] = true;14    q.push(0);15    while (!q.empty()) {16        int u = q.front();17        q.pop();18        cout << u << " ";19        for (int v : adj[u])20            if (!seen[v]) {21                seen[v] = true;22                q.push(v);23            }24    }25    cout << "\n";26    return 0;27}
猜輸出猜錯也沒關係

同一個圖,從 0 出發做 DFS,印出什麼?

1#include <iostream>2#include <vector>3using namespace std;4 5vector<vector<int>> adj(6);6vector<bool> seen(6, false);7 8void dfs(int u) {9    seen[u] = true;10    cout << u << " ";11    for (int v : adj[u])12        if (!seen[v])13            dfs(v);14}15 16int main() {17    auto add = [](int u, int v) { adj[u].push_back(v); adj[v].push_back(u); };18    add(0, 3); add(0, 1); add(1, 4); add(3, 4); add(3, 2); add(4, 5); add(2, 5);19    dfs(0);20    cout << "\n";21    return 0;22}
猜輸出猜錯也沒關係

有向邊 2→0、3→0、3→1、0→4、1→4、4→5,Kahn 演算法印出什麼?

1#include <iostream>2#include <vector>3#include <queue>4using namespace std;5 6int main() {7    int n = 6;8    vector<vector<int>> adj(n);9    vector<int> indeg(n, 0);10    auto add = [&](int u, int v) { adj[u].push_back(v); indeg[v]++; };11    add(2, 0); add(3, 0); add(3, 1); add(0, 4); add(1, 4); add(4, 5);12    queue<int> q;13    for (int v = 0; v < n; v++)14        if (indeg[v] == 0) q.push(v);15    while (!q.empty()) {16        int u = q.front();17        q.pop();18        cout << u << " ";19        for (int v : adj[u])20            if (--indeg[v] == 0)21                q.push(v);22    }23    cout << "\n";24    return 0;25}
猜輸出猜錯也沒關係

從 0 出發的 Dijkstra(priority_queue 版),dist 是多少?

1#include <iostream>2#include <vector>3#include <queue>4#include <functional>5#include <utility>6using namespace std;7 8typedef pair<int, int> P;9 10int main() {11    int n = 5;12    vector<vector<P>> g(n);13    auto add = [&](int u, int v, int w) { g[u].push_back({v, w}); g[v].push_back({u, w}); };14    add(0, 1, 5); add(0, 2, 1); add(2, 1, 2); add(1, 3, 1);15    add(2, 3, 6); add(3, 4, 2); add(2, 4, 9);16    vector<int> dist(n, 1000000000);17    priority_queue<P, vector<P>, greater<P>> pq;18    dist[0] = 0;19    pq.push({0, 0});20    while (!pq.empty()) {21        int d = pq.top().first, u = pq.top().second;22        pq.pop();23        if (d > dist[u]) continue;24        for (const P& e : g[u])25            if (d + e.second < dist[e.first]) {26                dist[e.first] = d + e.second;27                pq.push({dist[e.first], e.first});28            }29    }30    for (int x : dist) cout << x << " ";31    cout << "\n";32    return 0;33}
猜輸出猜錯也沒關係

Kruskal 求最小生成樹,總權是多少?

1#include <iostream>2#include <vector>3#include <algorithm>4#include <numeric>5using namespace std;6 7struct Edge { int u, v, w; };8 9vector<int> parent(5);10 11int find(int x) {12    if (parent[x] != x) parent[x] = find(parent[x]);13    return parent[x];14}15 16int main() {17    iota(parent.begin(), parent.end(), 0);18    vector<Edge> e = {{0, 1, 2}, {0, 3, 6}, {1, 2, 3}, {1, 3, 8},19                      {1, 4, 5}, {2, 4, 7}, {3, 4, 9}};20    sort(e.begin(), e.end(), [](const Edge& a, const Edge& b) { return a.w < b.w; });21    int total = 0;22    for (const Edge& x : e) {23        int a = find(x.u), b = find(x.v);24        if (a != b) {25            parent[a] = b;26            total += x.w;27        }28    }29    cout << total << "\n";30    return 0;31}