class Graph {
adjacencyList: Map<number, number[]>;
constructor(edges: [number, number][]) {
this.adjacencyList = new Map();
for (const [u, v] of edges) {
if (!this.adjacencyList.has(u)) this.adjacencyList.set(u, []);
if (!this.adjacencyList.has(v)) this.adjacencyList.set(v, []);
this.adjacencyList.get(u)!.push(v);
this.adjacencyList.get(v)!.push(u);
}
}
isBipartite(): boolean {
const color = new Map<number, number>();
for (const node of this.adjacencyList.keys()) {
if (!color.has(node)) {
if (!this.dfsCheck(node, color, 0)) return false;
}
}
return true;
}
private dfsCheck(node: number, color: Map<number, number>, c: number): boolean {
color.set(node, c); // assign color to current node
for (const neighbor of this.adjacencyList.get(node)!) {
if (!color.has(neighbor)) {
if (!this.dfsCheck(neighbor, color, 1 - c)) return false; // assign opposite color
} else if (color.get(neighbor) === c) {
return false; // neighbor has same color, not bipartite
}
}
return true;
}
}
// Driver code
const edges: [number, number][] = [[1, 2], [2, 3], [3, 4], [4, 1]];
const graph = new Graph(edges);
console.log(graph.isBipartite() ? "Graph is bipartite" : "Graph is not bipartite");color.set(node, c); // assign color to current node
assign color to current node to mark its group
for (const neighbor of this.adjacencyList.get(node)!) {
check all neighbors of current node
if (!color.has(neighbor)) {
if neighbor not colored, assign opposite color recursively
if (!this.dfsCheck(neighbor, color, 1 - c)) return false; // assign opposite color
recursive call to color neighbor with opposite color
else if (color.get(neighbor) === c) {
if neighbor has same color, graph is not bipartite