Cycle Detection in Undirected Graph
Detects if a cycle exists in an undirected graph using Depth First Search (DFS).
#include <iostream>
#include <vector>
using namespace std;
bool dfs(int v, int parent, vector<vector<int>>& adj, vector<bool>& visited) {
visited[v] = true;
for (int u : adj[v]) {
if (!visited[u]) {
if (dfs(u, v, adj, visited)) return true;
} else if (u != parent)
return true;
}
return false;
}
int main() {
cout << "INSTRUCTIONS: Enter V (vertices) and E (edges), followed by E pairs of edges (u v)." << endl;
int V, E;
cin >> V >> E;
vector<vector<int>> adj(V);
vector<bool> visited(V, false);
for (int i = 0; i < E; i++) {
int u, v;
cin >> u >> v;
adj[u].push_back(v);
adj[v].push_back(u);
}
for (int i = 0; i < V; i++)
if (!visited[i] && dfs(i, -1, adj, visited)) {
cout << "Cycle Found";
return 0;
}
cout << "No Cycle";
}Cycle Detection in Undirected Graph — Free C++, C, Python Code Example
Detects if a cycle exists in an undirected graph using Depth First Search (DFS). This free code example is available in C++, C, Python and can be copied and run immediately — no account or signup required. Use the language tabs above to switch between implementations.
How to Use This Code
- Select your language — click the language tab (C, Java, C++, or Python) above the code viewer.
- Copy the code — use the copy button in the top-right corner of the code block.
- Run it — paste into a file with the correct extension (.c, .java, .cpp, .py), compile, and run using your terminal or IDE.
- Follow the on-screen instructions in the terminal to provide any required inputs.
Frequently Asked Questions
What does this program do?
Detects if a cycle exists in an undirected graph using Depth First Search (DFS).
Which languages is it available in?
Available in C++, C, Python. Switch between implementations using the tabs at the top of the code viewer.
How do I run this code?
Copy the code, save it with the right file extension (.c, .java, .cpp, or .py), then compile or run it with your installed compiler or interpreter (GCC, JDK, G++, Python 3).
Is this code free?
Yes — free to view, copy, and use. No account required.