從指定頂點出發,訪問圖中所有頂點且僅訪問一次。分為兩大策略:
類似樹的前序遍歷,遞迴實現:
void DFS(MGraph G, int v) {
visited[v] = TRUE;
VisitFunc(G.vexs[v]);
for (int w = 0; w < G.numVertexes; w++)
if (G.arc[v][w] != INFINITY && !visited[w])
DFS(G, w);
}
void DFS(GraphAdjList GL, int v) {
visited[v] = TRUE;
VisitFunc(GL->adjList[v].data);
for (EdgeNode *e = GL->adjList[v].firstedge; e; e = e->next)
if (!visited[e->adjvex])
DFS(GL, e->adjvex);
}
層層推進,需輔助佇列:
void BFS(MGraph G, int v) {
Queue Q;
EnQueue(Q, v);
visited[v] = TRUE;
VisitFunc(G.vexs[v]);
while (!QueueEmpty(Q)) {
DeQueue(Q, &v);
for (int w = 0; w < G.numVertexes; w++) {
if (G.arc[v][w] != INFINITY && !visited[w]) {
visited[w] = TRUE;
VisitFunc(G.vexs[w]);
EnQueue(Q, w);
}
}
}
}
void BFS(GraphAdjList GL, int v) {
Queue Q;
EnQueue(Q, v);
visited[v] = TRUE;
VisitFunc(GL->adjList[v].data);
while (!QueueEmpty(Q)) {
DeQueue(Q, &v);
for (EdgeNode *e = GL->adjList[v].firstedge; e; e = e->next) {
if (!visited[e->adjvex]) {
visited[e->adjvex] = TRUE;
VisitFunc(GL->adjList[e->adjvex].data);
EnQueue(Q, e->adjvex);
}
}
}
}
| 演算法 | 時間複雜度 (鄰接矩陣) | 時間複雜度 (鄰接表) | 空間複雜度 |
|---|---|---|---|
| DFS | O(n²) | O(n+e) | O(n) 遞迴棧/visited 陣列 |
| BFS | O(n²) | O(n+e) | O(n) 佇列/visited 陣列 |