-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy path886-possible-bipartition.js
More file actions
58 lines (55 loc) · 1.24 KB
/
886-possible-bipartition.js
File metadata and controls
58 lines (55 loc) · 1.24 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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
function Node(val) {
this.val = val
this.color = null
this.children = []
this.parents = []
}
/**
* @param {number} N
* @param {number[][]} dislikes
* @return {boolean}
*/
var possibleBipartition = function(N, dislikes) {
const graph = {}
// Build the graph
for(let dislike of dislikes) {
const [u,v] = dislike
graph[u] = graph[u] || new Node(u)
graph[u].children.push(v)
graph[v] = graph[v] || new Node(v)
graph[v].parents.push(u)
}
// color all the nodes
let seen = {}
let toExplore = []
const keys = Object.keys(graph)
let color = 1
for(let i=0; i<keys.length; i++) {
const key = keys[i]
if(!seen[key]) {
toExplore.push(key)
seen[key] = true
graph[key].color = color
}
// BFS
let node
while(toExplore.length) {
node = graph[toExplore.shift()]
if(node.parents.length===0 && node.color === null) {
node.color = 1
}
color = node.color
const next = node.children.concat(node.parents)
for(let c of next) {
if(!seen[c]) {
graph[c].color= -color
toExplore.push(c)
seen[c] = true
} else if(graph[c].color===color) {
return false
}
}
}
}
return true
};