使用BFS檢查有向圖連通性的C++程式
為了檢查圖的連通性,我們將嘗試使用任何遍歷演算法遍歷所有節點。遍歷完成後,如果存在任何未訪問的節點,則該圖未連線。

對於有向圖,我們將從所有節點開始遍歷以檢查連通性。有時一條邊可能只有向外的邊而沒有向內的邊,因此該節點將無法從任何其他起始節點訪問。
在這種情況下,遍歷演算法是遞迴BFS遍歷。
輸入 - 圖的鄰接矩陣
| 0 | 1 | 0 | 0 | 0 |
| 0 | 0 | 1 | 0 | 0 |
| 0 | 0 | 0 | 1 | 1 |
| 1 | 0 | 0 | 0 | 0 |
| 0 | 1 | 0 | 0 | 0 |
輸出 - 圖是連通的。
演算法
traverse(s, visited)
輸入:起始節點s和已訪問節點,用於標記哪些節點已訪問。
輸出:遍歷所有連線的頂點。
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 End
isConnected(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示例程式碼
#include<iostream>
#include<queue>
#define NODE 5
using namespace std;
int graph[NODE][NODE] = {
{0, 1, 0, 0, 0},
{0, 0, 1, 0, 0},
{0, 0, 0, 1, 1},
{1, 0, 0, 0, 0},
{0, 1, 0, 0, 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.
廣告
資料結構
網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP