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

방향 그래프의 경우 연결을 확인하기 위해 모든 노드에서 순회를 시작합니다. 때때로 한 가장자리에는 바깥쪽 가장자리만 있고 안쪽 가장자리는 없을 수 있으므로 해당 노드는 다른 시작 노드에서 방문하지 않습니다.
이 경우 순회 알고리즘은 재귀적 DFS 순회입니다.
입력 − 그래프의 인접 행렬
| 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(u, visited) Input: The start node u and the visited node to mark which node is visited. Output: Traverse all connected vertices. Begin mark u as visited for all vertex v, if it is adjacent with u, do if v is not visited, then traverse(v, visited) done End isConnected(graph) Input: The graph. Output: True if the graph is connected. 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>
#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 u, bool visited[]){
visited[u] = true; //mark v as visited
for(int v = 0; v<NODE; v++){
if(graph[u][v]){
if(!visited[v])
traverse(v, visited);
}
}
}
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.