Uh oh!
There was an error while loading. Please reload this page.
forked from trekhleb/javascript-algorithms
- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdetectUndirectedCycleUsingDisjointSet.js
More file actions
Latest commit
31 lines (28 loc) · 1.15 KB
/
Copy pathdetectUndirectedCycleUsingDisjointSet.js
File metadata and controls
31 lines (28 loc) · 1.15 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
importDisjointSetfrom'../../../data-structures/disjoint-set/DisjointSet';
/**
* Detect cycle in undirected graph using disjoint sets.
*
* @param {Graph} graph
*/
exportdefaultfunctiondetectUndirectedCycleUsingDisjointSet(graph){
// Create initial singleton disjoint sets for each graph vertex.
/** @param {GraphVertex} graphVertex */
constkeyExtractor=graphVertex=>graphVertex.getKey();
constdisjointSet=newDisjointSet(keyExtractor);
graph.getAllVertices().forEach(graphVertex=>disjointSet.makeSet(graphVertex));
// Go trough all graph edges one by one and check if edge vertices are from the
// different sets. In this case joint those sets together. Do this until you find
// an edge where to edge vertices are already in one set. This means that current
// edge will create a cycle.
letcycleFound=false;
/** @param {GraphEdge} graphEdge */
graph.getAllEdges().forEach((graphEdge)=>{
if(disjointSet.inSameSet(graphEdge.startVertex,graphEdge.endVertex)){
// Cycle found.
cycleFound=true;
}else{
disjointSet.union(graphEdge.startVertex,graphEdge.endVertex);
}
});
returncycleFound;
}