C++ 程式檢查無向圖的連通性使用 BFS
想要檢查圖的連線性,我們將嘗試使用任意遍歷演算法遍歷所有節點。遍歷完成後,如果仍有未訪問的節點,則說明圖不是連通的。

對於無向圖,我們將選擇一個節點並從中進行遍歷。
本例中,遍歷演算法是遞迴 BFS 遍歷。
輸入 − 圖的鄰接矩陣
| 0 | 1 | 1 | 0 | 0 |
| 1 | 0 | 1 | 1 | 0 |
| 1 | 1 | 0 | 1 | 1 |
| 0 | 1 | 1 | 0 | 1 |
| 0 | 0 | 1 | 1 | 0 |
輸出 − 圖已連線。
演算法
traverse(s, visited)
輸入 − 開始節點 s 和 visited 節點,用於標記哪個節點已被訪問。
輸出 − 遍歷所有連線的頂點。
Begin
mark s as visited
insert s into a queue Q
until the Q is not empty, do
u = node that is taken out from the queue
for each node v of the graph, do
if the u and v are connected, then
if u is not visited, then
mark u as visited
insert u into the queue Q.
done
done
EndisConnected(graph)
輸入 − 圖。
輸出 − 如果圖連通,則返回 True。
Begin
define visited array
for all vertices u in the graph, do
make all nodes unvisited
traverse(u, visited)
if any unvisited node is still remaining, then
return false
done
return true
End示例程式碼 (C++)
#include<iostream>
#include<queue>
#define NODE 5
using namespace std;
int graph[NODE][NODE] = {
{0, 1, 1, 0, 0},
{1, 0, 1, 1, 0},
{1, 1, 0, 1, 1},
{0, 1, 1, 0, 1},
{0, 0, 1, 1, 0}};
void traverse(int s, bool visited[]) {
visited[s] = true; //mark v as visited
queue<int> que;
que.push(s);//insert s into queue
while(!que.empty()) {
int u = que.front(); //delete from queue and print
que.pop();
for(int i = 0; i < NODE; i++) {
if(graph[i][u]) {
//when the node is non-visited
if(!visited[i]) {
visited[i] = true;
que.push(i);
}
}
}
}
}
bool isConnected() {
bool *vis = new bool[NODE];
//for all vertex u as start point, check whether all nodes are visible or not
for(int u; u < NODE; u++) {
for(int i = 0; i < NODE; i++)
vis[i] = false; //initialize as no node is visited
traverse(u, vis);
for(int i = 0; i < NODE; i++) {
if(!vis[i]) //if there is a node, not visited by traversal, graph is not connected
return false;
}
}
return true;
}
int main() {
if(isConnected())
cout << "The Graph is connected.";
else
cout << "The Graph is not connected.";
}輸出
The Graph is connected.
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP