function hasCycle(graph) {
const visited = new Set();
function dfs(node, parent) {
visited.add(node);
for (const neighbor of graph[node]) {
if (!visited.has(neighbor)) {
if (dfs(neighbor, node)) return true;
} else if (neighbor !== parent) {
return true;
}
}
return false;
}
for (const node in graph) {
if (!visited.has(node)) {
if (dfs(node, null)) return true;
}
}
return false;
}
const graph = {
0: [1, 2],
1: [0, 2],
2: [0, 1, 3],
3: [2, 4],
4: [3]
};
console.log(hasCycle(graph));The graph contains a cycle between nodes 0, 1, and 2. The DFS detects this cycle and returns true.
class UnionFind { constructor(size) { this.parent = Array(size).fill(0).map((_, i) => i); this.rank = Array(size).fill(0); } find(x) { if (this.parent[x] !== x) { this.parent[x] = this.find(this.parent[x]); } return this.parent[x]; } union(x, y) { const rootX = this.find(x); const rootY = this.find(y); if (rootX === rootY) return false; if (this.rank[rootX] < this.rank[rootY]) { this.parent[rootX] = rootY; } else if (this.rank[rootX] > this.rank[rootY]) { this.parent[rootY] = rootX; } else { this.parent[rootY] = rootX; this.rank[rootX]++; } return true; } } function hasCycle(edges, n) { const uf = new UnionFind(n); for (const [u, v] of edges) { if (!uf.union(u, v)) { return true; } } return false; } const edges = [[0,1],[1,2],[2,0],[3,4]]; const n = 5; console.log(hasCycle(edges, n));
The edges form a cycle between nodes 0, 1, and 2. The union operation returns false on the third edge, so the function returns true.
function hasCycle(graph) {
const visited = new Set();
function dfs(node, parent) {
visited.add(node);
for (const neighbor of graph[node]) {
if (!visited.has(neighbor)) {
if (dfs(neighbor, node)) return true;
} else if (neighbor !== parent) {
return true;
}
}
return false;
}
for (const node in graph) {
if (!visited.has(node)) {
if (dfs(node, null)) return true;
}
}
return false;
}
const graph = {
0: [1],
1: [0, 2],
2: [1]
};
console.log(hasCycle(graph));The recursive call dfs(neighbor) misses the parent argument, so inside dfs the parent parameter is undefined, causing graph[undefined] to be accessed, which is undefined, leading to the TypeError when iterating.
function hasCycle(graph) {
const visited = new Set();
function dfs(node, parent) {
visited.add(node);
for (const neighbor of graph[node]) {
if (!visited.has(neighbor)) {
if (dfs(neighbor, node)) return true;
} else if (neighbor !== parent) {
return true;
}
}
return false;
}
for (const node in graph) {
if (!visited.has(node)) {
if (dfs(node, null)) return true;
}
}
return false;
}
const graph = {
0: [1],
1: [0],
2: [3],
3: [2, 4],
4: [3]
};
console.log(hasCycle(graph));The graph has two disconnected components, both are simple chains without cycles, so the function returns false.
If two nodes are already in the same set, connecting them again creates a cycle. Union-Find detects this by failing the union operation.
