圖 G = (V, E),V 為頂點有限非空集合,E 為邊集合。依邊是否有方向分為有向圖(弧 <Vi, Vj>)與無向圖(邊 (Vi, Vj))。無自迴路、無重複邊者稱簡單圖。
// 頂點類
function Vertex(label) {
this.label = label;
this.wasVisited = false;
}
// 圖類
function Graph(v) {
this.vertices = v;
this.edges = 0;
this.adj = []; // 鄰接表:adj[i] 存放第 i 個頂點的相鄰頂點陣列
this.marked = []; // 訪問標記
this.edgeTo = []; // 最短路徑回溯用
for (var i = 0; i < this.vertices; i++) {
this.adj[i] = [];
this.marked[i] = false;
}
}
// 新增邊(無向圖)
Graph.prototype.addEdge = function(v, w) {
this.adj[v].push(w);
this.adj[w].push(v);
this.edges++;
};
// 顯示圖結構
Graph.prototype.toString = function() {
var s = '';
for (var i = 0; i < this.vertices; i++) {
s += i + ' -> ';
for (var j = 0; j < this.adj[i].length; j++) {
s += this.adj[i][j] + ' ';
}
s += '\n';
}
return s;
};
Graph.prototype.dfs = function(v) {
this.marked[v] = true;
console.log('Visited vertex: ' + v);
for (var i = 0; i < this.adj[v].length; i++) {
var w = this.adj[v][i];
if (!this.marked[w]) {
this.dfs(w);
}
}
};
特性:沿單一路徑走到底再回溯,適合「尋找路徑是否存在」、「拓撲排序」、「連通分量」。
Graph.prototype.bfs = function(s) {
var queue = [];
this.marked[s] = true;
queue.push(s);
while (queue.length > 0) {
var v = queue.shift(); // 隊首出隊
console.log('Visited vertex: ' + v);
for (var i = 0; i < this.adj[v].length; i++) {
var w = this.adj[v][i];
if (!this.marked[w]) {
this.edgeTo[w] = v; // 記錄前驅節點
this.marked[w] = true;
queue.push(w);
}
}
}
};
特性:層層向外擴散,天然找到無權圖的最短路徑(邊數最少)。
// 呼叫 bfs(s) 後,edgeTo 已記錄從 s 到各節點的前驅
Graph.prototype.pathTo = function(v) {
if (!this.marked[v]) return null; // 不連通
var path = [];
for (var x = v; x !== s; x = this.edgeTo[x]) {
path.push(x);
}
path.push(s);
return path.reverse(); // 從起點到終點
};
適用於有向無環圖 (DAG),將頂點排序使所有邊從前指向後。
Graph.prototype.topSort = function() {
var stack = [];
var visited = [];
for (var i = 0; i < this.vertices; i++) visited[i] = false;
for (var i = 0; i < this.vertices; i++) {
if (!visited[i]) this.topSortHelper(i, visited, stack);
}
// stack 為反序,輸出時反轉
var result = [];
while (stack.length) {
var v = stack.pop();
if (v !== undefined && v !== false) result.push(this.vertexList[v]);
}
return result;
};
Graph.prototype.topSortHelper = function(v, visited, stack) {
visited[v] = true;
for (var i = 0; i < this.adj[v].length; i++) {
var w = this.adj[v][i];
if (!visited[w]) this.topSortHelper(w, visited, stack);
}
stack.push(v);
};
| 演算法 | 適用場景 | 時間複雜度 |
|---|---|---|
| DFS | 連通性判斷、環偵測、拓撲排序、解謎類(迷宮) | O(V+E) |
| BFS | 無權圖最短路徑、社交網絡度數、層級遍歷 | O(V+E) |
| 拓撲排序 | 任務調度、編譯依賴、課程先修關係 | O(V+E) |
掌握鄰接表儲存、DFS/BFS 兩大遍歷模板、最短路徑回溯與拓撲排序,即可解決 90% 以上前端面試與實務中的圖論問題。建議動手在 LeetCode 練習「Number of Islands」、「Course Schedule」、「Clone Graph」鞏固實力。