Detect Cycle in Undirected Connected Graph
Example: 1
True
Example: 2
False
Example: 3
True
Adjacent Lists
- 0: 1
- 1: 4, 2
- 2: 1, 3
- 3: 2, 4
- 4: 1, 3
Visited nodes: [0, 1, 4, 3, 2] So, It's not possible. Hence It is not a cycle.
Find Cycle ?
Note: To keep a track of parent of each node.
Parent:
Start from Node ‘A’
- A: Null
- B: A
- C: A
- D: C
- E: D
- H: E
- G: E
- F: H
A cycle exists if:
visited[node] == true AND node != parent
Code
function hasCycle(edges) {
let graph = {};
for(let [x, y] of edges) {
if (!graph[x]) graph[x] = [];
if (!graph[y]) graph[y] = [];
graph[x].push(y);
graph[y].push(x);
}
graph[x].push(y);
graph[y].push(x);
let visited = new Set();
let dfs = (curr, parent) => {
visited.add(curr);
for(let neighbor of graph[curr]) {
if(!visited.has(neighbor)) {
return dfs(neighbor, curr)
}
else if(neighbor != parent) {
//cycle exists
return true;
}
}
return false;
}
return dfs(0, -1);
}
console.log(hasCycle([[0, 1], [1, 2], [2, 0]]));
// true -> 0-1-2-0 forms a cycle
console.log(hasCycle([[0,1], [1, 2], [2, 3]]));
// false -> no back edge
console.log(hasCycle([[0, 1], [1, 2], [2, 3], [3, 4], [1, 4]]));
// true -> 1-2-3-4-1 forms a cycle
from collections import defaultdict
def hasCycle(edges):
graph = defaultdict(list)
for x, y in edges:
graph[x].append(y)
graph[y].append(x)
visited = set()
def dfs(curr, parent):
visited.add(curr)
for neighbor in graph[curr]:
if neighbor not in visited:
if dfs(neighbor, curr):
return True
elif neighbor != parent:
return True
return False
return dfs(edges[0][0], -1)
print(hasCycle([[0,1],[1,2],[2,0]])) # True
print(hasCycle([[0,1],[1,2],[2,3]])) # False
print(hasCycle([[0,1],[1,2],[2,3],[3,4],[1,4]])) # True
import java.util.*;
public class CycleDetection {
static boolean dfs(int curr, int parent, Map> graph, Set visited) {
visited.add(curr);
for (int neighbor : graph.get(curr)) {
if (!visited.contains(neighbor)) {
if (dfs(neighbor, curr, graph, visited)) return true;
} else if (neighbor != parent) {
return true;
}
}
return false;
}
static boolean hasCycle(int[][] edges) {
Map> graph = new HashMap<>();
for (int[] e : edges) {
graph.computeIfAbsent(e[0], k -> new ArrayList<>()).add(e[1]);
graph.computeIfAbsent(e[1], k -> new ArrayList<>()).add(e[0]);
}
return dfs(edges[0][0], -1, graph, new HashSet<>());
}
public static void main(String[] args) {
System.out.println(hasCycle(new int[][]{{0,1},{1,2},{2,0}}));
System.out.println(hasCycle(new int[][]{{0,1},{1,2},{2,3}}));
System.out.println(hasCycle(new int[][]{{0,1},{1,2},{2,3},{3,4},{1,4}}));
}
}
#include <bits/stdc++.h> using namespace std; bool dfs(int curr, int parent, unordered_map>& graph, unordered_set & visited) { visited.insert(curr); for (int neighbor : graph[curr]) { if (!visited.count(neighbor)) { if (dfs(neighbor, curr, graph, visited)) return true; } else if (neighbor != parent) { return true; // cycle detected } } return false; } bool hasCycle(vector > edges) { unordered_map > graph; for (auto [x, y] : edges) { graph[x].push_back(y); graph[y].push_back(x); } unordered_set visited; return dfs(edges[0].first, -1, graph, visited); } int main() { cout << hasCycle({{0,1},{1,2},{2,0}}) << endl; cout << hasCycle({{0,1},{1,2},{2,3}}) << endl; cout << hasCycle({{0,1},{1,2},{2,3},{3,4},{1,4}}) << endl; }
#include <stdio.h>
#include <stdlib.h>
#define MAX 100
int visited[MAX];
int graph[MAX][MAX];
int n = MAX;
int dfs(int curr, int parent) {
visited[curr] = 1;
for (int i = 0; i < n; i++) {
if (graph[curr][i]) {
if (!visited[i]) {
if (dfs(i, curr)) return 1;
} else if (i != parent) {
return 1;
}
}
}
return 0;
}
int main() {
graph[0][1] = graph[1][0] = 1;
graph[1][2] = graph[2][1] = 1;
graph[2][0] = graph[0][2] = 1;
printf("%d\n", dfs(0, -1)); // 1 = true
}
using System;
using System.Collections.Generic;
class CycleDetection {
static bool Dfs(int curr, int parent, Dictionary> graph, HashSet visited) {
visited.Add(curr);
foreach (int neighbor in graph[curr]) {
if (!visited.Contains(neighbor)) {
if (Dfs(neighbor, curr, graph, visited)) return true;
}
else if (neighbor != parent) {
return true;
}
}
return false;
}
static bool HasCycle(int[,] edges) {
var graph = new Dictionary>();
for (int i = 0; i < edges.GetLength(0); i++) {
int x = edges[i, 0], y = edges[i, 1];
if (!graph.ContainsKey(x)) graph[x] = new List();
if (!graph.ContainsKey(y)) graph[y] = new List();
graph[x].Add(y);
graph[y].Add(x);
}
return Dfs(edges[0,0], -1, graph, new HashSet());
}
static void Main() {
Console.WriteLine(HasCycle(new int[,]{{0,1},{1,2},{2,0}}));
Console.WriteLine(HasCycle(new int[,]{{0,1},{1,2},{2,3}}));
Console.WriteLine(HasCycle(new int[,]{{0,1},{1,2},{2,3},{3,4},{1,4}}));
}
}
Add A Comment
