Skip to content

Commit f59275e

Browse files
authored
Create 886-possible-bipartition.js
1 parent 7ade96f commit f59275e

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed

886-possible-bipartition.js

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
/**
2+
* @param {number} N
3+
* @param {number[][]} dislikes
4+
* @return {boolean}
5+
*/
6+
const possibleBipartition = function(N, dislikes) {
7+
const graph = []
8+
for(let i = 0; i <= N; i++) {
9+
graph[i] = []
10+
}
11+
for(let el of dislikes) {
12+
graph[el[0]].push(el[1])
13+
graph[el[1]].push(el[0])
14+
}
15+
const color = new Array(N+1).fill(0)
16+
for (let i = 1; i <= N; i++) {
17+
if (color[i] == 0) {
18+
color[i] = 1;
19+
const q = [];
20+
q.push(i);
21+
while (q.length > 0) {
22+
let cur = q.shift();
23+
for (let j of graph[cur]) {
24+
if (color[j] == 0) {
25+
color[j] = color[cur] == 1 ? 2 : 1;
26+
q.push(j);
27+
} else {
28+
if (color[j] == color[cur]) return false;
29+
}
30+
}
31+
}
32+
}
33+
}
34+
return true
35+
};

0 commit comments

Comments
 (0)