Skip to content

Commit d2d28f0

Browse files
authored
feat: bipartite graph (TheAlgorithms#190)
1 parent 362f503 commit d2d28f0

File tree

2 files changed

+79
-0
lines changed

2 files changed

+79
-0
lines changed

graph/bipartite_graph.ts

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
const dfs = (
2+
graph: number[][],
3+
colors: number[],
4+
node: number,
5+
color: number
6+
): boolean => {
7+
if (colors[node] !== 0) {
8+
return colors[node] === color;
9+
}
10+
11+
colors[node] = color;
12+
13+
for (const neighbor of graph[node]) {
14+
if (!dfs(graph, colors, neighbor, -color)) {
15+
return false;
16+
}
17+
}
18+
19+
return true;
20+
};
21+
22+
23+
/**
24+
* Determines if a given graph is bipartite.
25+
*
26+
* A Bipartite Graph is a graph whose vertices can be divided into two independent sets,
27+
* U and V such that every edge (u, v) either connects a vertex from U to V or a vertex from
28+
* V to U
29+
*
30+
* @param {number[][]} graph - The graph represented as an adjacency list.
31+
* @returns {boolean} - `true` if the graph is bipartite, `false` otherwise.
32+
*/
33+
34+
35+
export const isBipartite = (graph: number[][]): boolean => {
36+
const n: number = graph.length;
37+
const colors: number[] = new Array(n).fill(0);
38+
39+
for (let i = 0; i < n; i++) {
40+
if (colors[i] === 0 && !dfs(graph, colors, i, 1)) {
41+
return false;
42+
}
43+
}
44+
45+
return true;
46+
};

graph/test/bipartite_graph.test.ts

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
import { isBipartite } from "../bipartite_graph";
2+
3+
describe('isBipartite', () => {
4+
it('should return true for a bipartite graph', () => {
5+
const graph = [[1, 3], [0, 2], [1, 3], [0, 2]];
6+
const result = isBipartite(graph);
7+
expect(result).toBe(true);
8+
});
9+
10+
it('should return true for an empty graph', () => {
11+
const graph: number[][] = [];
12+
const result = isBipartite(graph);
13+
expect(result).toBe(true);
14+
});
15+
16+
it('should return true for a single node graph', () => {
17+
const graph = [[]];
18+
const result = isBipartite(graph);
19+
expect(result).toBe(true);
20+
});
21+
22+
it('should return false for a non-bipartite graph', () => {
23+
const graph = [[1, 2, 3], [0, 2], [0, 1, 3], [0, 2]];
24+
const result = isBipartite(graph);
25+
expect(result).toBe(false);
26+
});
27+
28+
it('should return true for a disconnected bipartite graph', () => {
29+
const graph = [[1, 2], [0], [0], [4], [3]];
30+
const result = isBipartite(graph);
31+
expect(result).toBe(true);
32+
});
33+
});

0 commit comments

Comments
 (0)