그래프의 연결성을 확인하기 위해 순회 알고리즘을 사용하여 모든 노드를 순회하려고 합니다. 순회 완료 후 방문하지 않은 노드가 있으면 그래프가 연결되지 않습니다.

방향 그래프의 경우 연결을 확인하기 위해 모든 노드에서 순회를 시작합니다. 때때로 한 가장자리는 바깥쪽 가장자리만 가질 수 있지만 안쪽 가장자리는 없을 수 있으므로 해당 노드는 다른 시작 노드에서 방문하지 않습니다.
이 경우 순회 알고리즘은 재귀적 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 |
출력 − 그래프가 연결되었습니다.
알고리즘
횡단(들, 방문)
입력 :시작 노드와 방문한 노드를 표시하기 위해 방문한 노드입니다.
출력 :연결된 모든 정점을 순회합니다.
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
연결됨(그래프)
입력 - 그래프.
출력 − 그래프가 연결되어 있으면 참입니다.
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.