방향 그래프에서 구성 요소는 한 구성 요소의 각 꼭짓점 쌍 사이에 경로가 있을 때 강하게 연결되어 있다고 합니다.

이 알고리즘을 해결하기 위해 먼저 DFS 알고리즘을 사용하여 각 정점의 종료 시간을 구하고 이제 전치된 그래프의 종료 시간을 찾은 다음 정점을 토폴로지 정렬에 따라 내림차순으로 정렬합니다.
입력 :그래프의 인접 행렬입니다.
| 0 | 0 | 1 | 1 | 0 |
| 1 | 0 | 0 | 0 | 0 |
| 0 | 1 | 0 | 0 | 0 |
| 0 | 0 | 0 | 0 | 1 |
| 0 | 0 | 0 | 0 | 0 |
출력 :다음은 주어진 그래프에서 강력하게 연결된 구성 요소입니다 -
0 1 2 3 4
알고리즘
traverse(그래프, 시작, 방문)
입력 :순회할 그래프, 시작 정점, 방문 플래그
노드.
출력 :DFS 기법으로 각 노드를 탐색하고 노드를 표시합니다.
Begin mark start as visited for all vertices v connected with start, do if v is not visited, then traverse(graph, v, visited) done End
topoSort(u, 방문, 스택)
입력 − 시작 노드, 방문한 정점에 대한 플래그, 스택.
출력 − 그래프를 정렬하는 동안 스택을 채웁니다.
Begin mark u as visited for all node v, connected with u, do if v is not visited, then topoSort(v, visited, stack) done push u into the stack End
getStrongConComponents(그래프)
입력 - 주어진 그래프.
출력 − 강력하게 연결된 모든 구성 요소.
Begin initially all nodes are unvisited for all vertex i in the graph, do if i is not visited, then topoSort(i, vis, stack) done make all nodes unvisited again transGraph := transpose of given graph while stack is not empty, do pop node from stack and take into v if v is not visited, then traverse(transGraph, v, visited) done End
예시 코드
#include <iostream>
#include <stack>
#define NODE 5
using namespace std;
int graph[NODE][NODE]= {
{0, 0, 1, 1, 0},
{1, 0, 0, 0, 0},
{0, 1, 0, 0, 0},
{0, 0, 0, 0, 1},
{0, 0, 0, 0, 0}};
int transGraph[NODE][NODE];
void transpose() { //transpose the graph and store to transGraph
for(int i = 0; i<NODE; i++)
for(int j = 0; j<NODE; j++)
transGraph[i][j] = graph[j][i];
}
void traverse(int g[NODE][NODE], int u, bool visited[]) {
visited[u] = true; //mark v as visited
cout << u << " ";
for(int v = 0; v<NODE; v++) {
if(g[u][v]) {
if(!visited[v])
traverse(g, v, visited);
}
}
}
void topoSort(int u, bool visited[], stack<int> &stk) {
visited[u] = true; //set as the node v is visited
for(int v = 0; v<NODE; v++) {
if(graph[u][v]) { //for allvertices v adjacent to u
if(!visited[v])
topoSort(v, visited, stk);
}
}
stk.push(u); //push starting vertex into the stack
}
void getStrongConComponents() {
stack<int> stk;
bool vis[NODE];
for(int i = 0; i<NODE; i++)
vis[i] = false; //initially all nodes are unvisited
for(int i = 0; i<NODE; i++)
if(!vis[i]) //when node is not visited
topoSort(i, vis, stk);
for(int i = 0; i<NODE; i++)
vis[i] = false; //make all nodes are unvisited for traversal
transpose(); //make reversed graph
while(!stk.empty()) { //when stack contains element, process in topological order
int v = stk.top(); stk.pop();
if(!vis[v]) {
traverse(transGraph, v, vis);
cout << endl;
}
}
}
int main() {
cout << "Following are strongly connected components in given graph: "<<endl;
getStrongConComponents();
} 출력
Following are strongly connected components in given graph: 0 1 2 3 4