-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
34 lines (32 loc) · 1.06 KB
/
index.ts
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
export default function isBipartite(graph: number[][]): boolean {
const color = graph.map(() => Colors.None);
for (const index of graph.keys()) {
if (color[index] === Colors.None) {
let queue = [index];
color[index] = Colors.One;
while (queue.length) {
const temp: number[] = [];
for (const node of queue) {
const neighbor_color = color[node] === Colors.One
? Colors.Two
: Colors.One;
for (const neighbor of graph[node]) {
if (color[neighbor] === Colors.None) {
temp.push(neighbor);
color[neighbor] = neighbor_color;
} else if (color[neighbor] !== neighbor_color) {
return false;
}
}
}
queue = temp;
}
}
}
return true;
}
const enum Colors {
One,
Two,
None,
}