-
-
Notifications
You must be signed in to change notification settings - Fork 408
/
Copy pathbipartite_graph.ts
44 lines (37 loc) · 1011 Bytes
/
bipartite_graph.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
35
36
37
38
39
40
41
42
43
44
const dfs = (
graph: number[][],
colors: number[],
node: number,
color: number
): boolean => {
if (colors[node] !== 0) {
return colors[node] === color
}
colors[node] = color
for (const neighbor of graph[node]) {
if (!dfs(graph, colors, neighbor, -color)) {
return false
}
}
return true
}
/**
* Determines if a given graph is bipartite.
*
* A Bipartite Graph is a graph whose vertices can be divided into two independent sets,
* U and V such that every edge (u, v) either connects a vertex from U to V or a vertex from
* V to U
*
* @param {number[][]} graph - The graph represented as an adjacency list.
* @returns {boolean} - `true` if the graph is bipartite, `false` otherwise.
*/
export const isBipartite = (graph: number[][]): boolean => {
const n: number = graph.length
const colors: number[] = new Array(n).fill(0)
for (let i = 0; i < n; i++) {
if (colors[i] === 0 && !dfs(graph, colors, i, 1)) {
return false
}
}
return true
}