Workspace N Queens
0d
Back to questionsDSA Visualizers: 388 Coding Questions

N Queens visualizer

Learn N Queens 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 / 18Execution step
Reference example · JavaScript
Inspect reference input
4

Algorithm source

JavaScript reference implementation · highlighted trace statement
const solve = (n,s)=>{
let o=[];
function f(p){
s("Place queens row by row",{
Columns:p,Solutions:o
});
if(p.length===n){
o.push(p);
return
}
for(let j=0;
j<n;
j++)if(p.every((x,i)=>x!==j&&Math.abs(x-j)!==p.length-i))f([...p,j])
}
f([]);
return o
};

Execution canvas

Active Changed
STEP 1

Place queens row by row

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

Columns0 items

Empty at this step.

Solutions0 items

Empty at this step.

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

4

Execution steps

  1. Place queens row by row

Computed output

[
  [
    1,
    3,
    0,
    2
  ],
  [
    2,
    0,
    3,
    1
  ]
]
JavaScript reference implementation
const solve = (n,s)=>{
  let o=[];
  function f(p){
    s("Place queens row by row",{
      Columns:p,Solutions:o
    });
    if(p.length===n){
      o.push(p);
      return
    }
    for(let j=0;
    j<n;
    j++)if(p.every((x,i)=>x!==j&&Math.abs(x-j)!==p.length-i))f([...p,j])
  }
  f([]);
  return o
};

Continue learning

Practice related DSA questions in the same topic.