Skip to content

Commit 543cd25

Browse files
committed
Create 785. 判断二分图.js
1 parent c93333c commit 543cd25

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed

785. 判断二分图.js

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

0 commit comments

Comments
 (0)