1. Two colors
0 uncolored, then 1 and -1 for the two sides.
const color = new Array(n).fill(0)Typorithm · medium
Step 1 of 8 · intro card
Graph Algorithms
BFS two-color the graph; a same-color edge between neighbors means it is not bipartite.
A graph is bipartite if its nodes split into two sets with every edge crossing between them.
BFS assigns each node the opposite color of its parent, spreading two colors outward.
If an edge ever connects two nodes of the same color, no valid split exists.
Neighbors get opposite colors.
Same-color edge = not bipartite.
Repeat for every component.
function isBipartite(graph, n) {
const color = new Array(n).fill(0);
for (let start = 0; start < n; start += 1) {
if (color[start] !== 0) continue;
color[start] = 1;
const queue = [start];
while (queue.length > 0) {
const node = queue.shift();
for (const next of graph[node]) {
if (color[next] === 0) {
color[next] = -color[node];
queue.push(next);
} else if (color[next] === color[node]) {
return false;
}
}
}
}
return true;
}Connect each part of the code to the concept before you type.
0 uncolored, then 1 and -1 for the two sides.
const color = new Array(n).fill(0)Restart coloring for every unvisited component.
if (color[start] !== 0) continueA neighbor must get the opposite color of the current node.
color[next] = -color[node]Two adjacent nodes with the same color make the graph non-bipartite.
else if (color[next] === color[node])A same-color edge proves no valid two-coloring exists.
return falseRead the concept map and follow the code breakdown.
Type the implementation, repair mistakes and work through every recall exercise.
Use the final check without hints; revisit weak concepts in short practice sessions.
Algorithm lab · interactive
InputUndirected graph · start A · edges A–B:4, A–D:2, B–C:3, B–E:1, D–E:5, E–F:2, C–F:4
Follow temporary values, local state and supporting structures at this step.
colors · nodes A–F6 entries
Around this step
Small, reproducible examples · ← → step · Space play/pause · Home/End first/last state