Skip to content

Commit

Permalink
feat: bipartite graph (#190)
Browse files Browse the repository at this point in the history
  • Loading branch information
Suryac72 authored Oct 12, 2023
1 parent 362f503 commit d2d28f0
Show file tree
Hide file tree
Showing 2 changed files with 79 additions and 0 deletions.
46 changes: 46 additions & 0 deletions graph/bipartite_graph.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
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;
};
33 changes: 33 additions & 0 deletions graph/test/bipartite_graph.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import { isBipartite } from "../bipartite_graph";

describe('isBipartite', () => {
it('should return true for a bipartite graph', () => {
const graph = [[1, 3], [0, 2], [1, 3], [0, 2]];
const result = isBipartite(graph);
expect(result).toBe(true);
});

it('should return true for an empty graph', () => {
const graph: number[][] = [];
const result = isBipartite(graph);
expect(result).toBe(true);
});

it('should return true for a single node graph', () => {
const graph = [[]];
const result = isBipartite(graph);
expect(result).toBe(true);
});

it('should return false for a non-bipartite graph', () => {
const graph = [[1, 2, 3], [0, 2], [0, 1, 3], [0, 2]];
const result = isBipartite(graph);
expect(result).toBe(false);
});

it('should return true for a disconnected bipartite graph', () => {
const graph = [[1, 2], [0], [0], [4], [3]];
const result = isBipartite(graph);
expect(result).toBe(true);
});
});

0 comments on commit d2d28f0

Please sign in to comment.