function isBipartite(graph) {
const n = graph.length;
const colors = new Array(n).fill(-1);
for (let i = 0; i < n; i++) {
if (colors[i] === -1) {
const queue = [i];
colors[i] = 0;
while (queue.length) {
const node = queue.shift();
for (const neighbor of graph[node]) {
if (colors[neighbor] === -1) {
colors[neighbor] = 1 - colors[node];
queue.push(neighbor);
} else if (colors[neighbor] === colors[node]) {
return false;
}
}
}
}
}
return true;
}
const graph = [[1,3],[0,2],[1,3],[0,2]];
console.log(isBipartite(graph));The graph is a square (4 nodes connected in a cycle of length 4). Such a cycle with even length is bipartite. The function colors nodes alternately and finds no conflicts, so it returns true.
function isBipartite(graph) {
const n = graph.length;
const colors = new Array(n).fill(-1);
for (let i = 0; i < n; i++) {
if (colors[i] === -1) {
const queue = [i];
colors[i] = 0;
while (queue.length) {
const node = queue.shift();
for (const neighbor of graph[node]) {
if (colors[neighbor] === -1) {
colors[neighbor] = 1 - colors[node];
queue.push(neighbor);
} else if (colors[neighbor] === colors[node]) {
return false;
}
}
}
}
}
return true;
}
const graph = [[1,2],[0,2],[0,1]];
console.log(isBipartite(graph));The graph is a triangle (3 nodes all connected). Odd cycles are not bipartite because you cannot color nodes with two colors without conflict. The function detects this and returns false.
BFS explores nodes level by level, which naturally fits the two-color assignment for bipartite checking. It helps detect conflicts between nodes in the same or adjacent levels easily.
function isBipartite(graph) {
const n = graph.length;
const colors = new Array(n).fill(-1);
for (let i = 0; i < n; i++) {
if (colors[i] === -1) {
const queue = [i];
colors[i] = 0;
while (queue.length) {
const node = queue.shift();
for (const neighbor of graph[node]) {
if (colors[neighbor] === -1) {
colors[neighbor] = 1 - colors[node];
queue.push(neighbor);
} else if (colors[neighbor] === colors[node]) {
return false;
}
}
}
}
}
return true;
}
const graph = [[1],[0],[]];
console.log(isBipartite(graph));The graph has two connected components: one edge between nodes 0 and 1, and node 2 isolated. Both components are bipartite, so the function returns true.
A graph is bipartite exactly when it has no cycles of odd length. Odd cycles prevent proper two-coloring, while even cycles do not.
