Skip to content

Commit 6fd7660

Browse files
committed
684. add graph solution
1 parent e2a8edc commit 6fd7660

1 file changed

Lines changed: 65 additions & 0 deletions

File tree

‎684. Redundant Connection.js‎

Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,71 @@ Return an edge that can be removed so that the resulting graph is a tree of N no
1212
multiple answers, return the answer that occurs last in the given 2D-array. The answer edge [u, v]
1313
should be in the same format, with u < v.
1414
*/
15+
/**
16+
* @param {number[][]} edges
17+
* @return {number[]}
18+
*/
19+
var findRedundantConnection = function(edges) {
20+
let edgesObj = createGraph(edges)
21+
let states = createStates(edges)
22+
23+
for(let i=edges.length-1; i>=0; i--) {
24+
let notTree = false
25+
let [srcKey, destKey] = edges[i]
26+
removeEdge(edgesObj, srcKey, destKey)
27+
// detect valid tree structure
28+
for(let start=1; start<=edges.length; start++) {
29+
if(hasCycle(start, edgesObj, {...states})) {
30+
notTree = true
31+
addEdge(edgesObj, srcKey, destKey)
32+
break
33+
}
34+
}
35+
if(notTree) continue
36+
return [srcKey, destKey]
37+
}
38+
};
39+
40+
function hasCycle(start, edgesObj, states, parentKey=start) {
41+
states[start] = 'VISITED'
42+
for(let destKey of edgesObj[start]) {
43+
if(states[destKey]==='VISITED' && destKey!==parentKey) return true
44+
if(states[destKey]==='UNVISITED' && hasCycle(destKey, edgesObj, states, start)) return true
45+
}
46+
return false
47+
}
48+
49+
function createStates(edges) {
50+
const states = {}
51+
for(let i=1; i<=edges.length; i++) {
52+
states[i] = 'UNVISITED'
53+
}
54+
return states
55+
}
56+
57+
function createGraph(edges) {
58+
const edgesObj = {}
59+
for(let edge of edges) {
60+
let srcKey = edge[0]
61+
let destKey = edge[1]
62+
if(!(srcKey in edgesObj)) edgesObj[srcKey] = new Set()
63+
edgesObj[srcKey].add(destKey)
64+
if(!(destKey in edgesObj)) edgesObj[destKey] = new Set()
65+
edgesObj[destKey].add(srcKey)
66+
}
67+
return edgesObj
68+
}
69+
70+
function removeEdge(edgesObj, srcKey, destKey) {
71+
edgesObj[srcKey].delete(destKey)
72+
edgesObj[destKey].delete(srcKey)
73+
}
74+
75+
function addEdge(edgesObj, srcKey, destKey) {
76+
edgesObj[srcKey].add(destKey)
77+
edgesObj[destKey].add(srcKey)
78+
}
79+
1580
/**
1681
* Algorithm: Union Find
1782
*/

0 commit comments

Comments
 (0)