检测无向图中的简单回路
在这篇文章中,我们将介绍如何使用深度优先搜索算法检测无向图中是否存在从给定顶点开始的简单回路。我们将使用 C++ 实现来演示。
C++ 代码
#include <iostream>
#include <vector>
#include <unordered_set>
using namespace std;
class Graph {
public:
int vertices;
vector<vector<int>> adjacencyList;
Graph(int vertices) : vertices(vertices), adjacencyList(vertices) {}
void addEdge(int v, int w) {
adjacencyList[v].push_back(w);
adjacencyList[w].push_back(v);
}
bool hasSimpleCycle(int V) {
unordered_set<int> visited;
vector<int> parent(vertices, -1);
return dfs(V, visited, parent, -1);
}
private:
bool dfs(int node, unordered_set<int>& visited, vector<int>& parent, int prev) {
visited.insert(node);
for (int neighbor : adjacencyList[node]) {
if (visited.find(neighbor) == visited.end()) {
parent[neighbor] = node;
if (dfs(neighbor, visited, parent, node)) {
return true;
}
} else if (neighbor != prev && parent[node] != neighbor) {
return true;
}
}
return false;
}
};
int main() {
Graph graph(4);
graph.addEdge(0, 1);
graph.addEdge(1, 2);
graph.addEdge(2, 3);
graph.addEdge(3, 0);
int startVertex = 0;
bool result = graph.hasSimpleCycle(startVertex);
if (result) {
cout << "Graph has a simple cycle starting from vertex " << startVertex << endl;
} else {
cout << "Graph has no simple cycle." << endl;
}
return 0;
}