用 C++ 打印无向图中的所有环
在这个问题中,我们给定一个无向图,我们需要打印图中形成的所有环。
无向图是一个相互连接的图。无向图的所有边都是双向的。它也称为无向网络。
图数据结构中的环是指所有顶点都形成一个环的图。
让我们看一个例子来更好地理解这个问题 -
图 -
输出 -
Cycle 1: 2 3 4 5 Cycle 2: 6 7 8
为此,我们将利用图的一些特性。您需要使用图着色方法并对出现在循环图中的所有顶点进行着色。此外,如果一个顶点被部分访问,它将导致一个循环图。因此,我们将对这个顶点和所有后续顶点进行着色,直到再次到达相同的顶点。
算法
Step 1: call DFS traversal for the graph which can color the vertices. Step 2: If a partially visited vertex is found, backtrack till the vertex is reached again and mark all vertices in the path with a counter which is cycle number. Step 3: After completion of traversal, iterate for cyclic edge and push them into a separate adjacency list. Step 4: Print the cycles number wise from the adjacency list.
示例
#include <bits/stdc++.h> using namespace std; const int N = 100000; vector<int> graph[N]; vector<int> cycles[N]; void DFSCycle(int u, int p, int color[], int mark[], int par[], int& cyclenumber){ if (color[u] == 2) { return; } if (color[u] == 1) { cyclenumber++; int cur = p; mark[cur] = cyclenumber; while (cur != u) { cur = par[cur]; mark[cur] = cyclenumber; } return; } par[u] = p; color[u] = 1; for (int v : graph[u]) { if (v == par[u]) { continue; } DFSCycle(v, u, color, mark, par, cyclenumber); } color[u] = 2; } void insert(int u, int v){ graph[u].push_back(v); graph[v].push_back(u); } void printCycles(int edges, int mark[], int& cyclenumber){ for (int i = 1; i <= edges; i++) { if (mark[i] != 0) cycles[mark[i]].push_back(i); } for (int i = 1; i <= cyclenumber; i++) { cout << "Cycle " << i << ": "; for (int x : cycles[i]) cout << x << " "; cout << endl; } } int main(){ insert(1, 2); insert(2, 3); insert(3, 4); insert(4, 5); insert(5, 2); insert(5, 6); insert(6, 7); insert(7, 8); insert(6, 8); int color[N]; int par[N]; int mark[N]; int cyclenumber = 0; cout<<"Cycles in the Graph are :\n"; int edges = 13; DFSCycle(1, 0, color, mark, par, cyclenumber); printCycles(edges, mark, cyclenumber); }
输出
图中的环 -
Cycle 1: 2 3 4 5 Cycle 2: 6 7 8
广告