Workspace Graph Coloring
0d
Back to questionsDSA Visualizers: 388 Coding Questions

Graph Coloring visualizer

Learn Graph Coloring with a step-by-step Recursion & Backtracking visualizer, JavaScript source code and a worked example. Practice constraint search.

INTERACTIVE EXECUTION STUDIO
LEARN BY DOING

Predict. Execute. Understand.

Follow the source code, inspect live state changes, and predict the next operation before revealing it.

1 / 4Execution step
Reference example · JavaScript
Inspect reference input
{
  "a": [
    [
      0,
      1,
      1
    ],
    [
      1,
      0,
      1
    ],
    [
      1,
      1,
      0
    ]
  ],
  "k": 3
}

Algorithm source

JavaScript reference implementation · highlighted trace statement
const solve = ({
a,k
},s)=>{
let c=Array(a.length).fill(0);
function f(i){
if(i===a.length)return true;
for(let x=1;
x<=k;
x++){
if(a[i].every((e,j)=>!e||c[j]!==x)){
c[i]=x;
s("Assign safe color",{
Graph:a,Colors:c
},[i]);
if(f(i+1))return true;
c[i]=0
}
}
return false
}
return f(0)?c:[]
};

Execution canvas

Active Changed
STEP 1

Assign safe color

Inspect the highlighted code and the state below. Click individual cells or nodes to see their values.

Graph3 rows
Colors3 items
Keyboard: Space to play · Left / Right to stepExplore next problem

Worked example and algorithm walkthrough

Topic: Recursion & Backtracking · Constraint search

Follow the computed execution on the reference input. Advance one step at a time, inspect the changing values and compare your prediction with the final output.

Example input

{
  "a": [
    [
      0,
      1,
      1
    ],
    [
      1,
      0,
      1
    ],
    [
      1,
      1,
      0
    ]
  ],
  "k": 3
}

Execution steps

  1. Assign safe color

Computed output

[
  1,
  2,
  3
]
JavaScript reference implementation
const solve = ({
  a,k
},s)=>{
  let c=Array(a.length).fill(0);
  function f(i){
    if(i===a.length)return true;
    for(let x=1;
    x<=k;
    x++){
      if(a[i].every((e,j)=>!e||c[j]!==x)){
        c[i]=x;
        s("Assign safe color",{
          Graph:a,Colors:c
        },[i]);
        if(f(i+1))return true;
        c[i]=0
      }
    }
    return false
  }
  return f(0)?c:[]
};

Continue learning

Practice related DSA questions in the same topic.