Workspace Number Of Provinces
0d
Back to questionsDSA Visualizers: 388 Coding Questions

Number of Provinces visualizer

Learn Number of Provinces with a step-by-step Graphs visualizer, JavaScript source code and a worked example. Practice traversal and connectivity.

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
[
  [
    1,
    1,
    0
  ],
  [
    1,
    1,
    0
  ],
  [
    0,
    0,
    1
  ]
]

Algorithm source

JavaScript reference implementation · highlighted trace statement
const solve = (a,s)=>{
let seen=new Set,c=0;
for(let i=0;
i<a.length;
i++)if(!seen.has(i)){
c++;
let q=[i];
seen.add(i);
while(q.length){
let u=q.shift();
for(let v=0;
v<a.length;
v++)if(a[u][v]&&!seen.has(v)){
seen.add(v);
q.push(v)
}
s("Explore connected province",{
Matrix:a,Queue:q,Visited:[...seen],Count:[c]
})
}
}
return c
};

Execution canvas

Active Changed
STEP 1

Explore connected province

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

Matrix3 rows
Queue1 items
Visited2 items
Count1 items
Keyboard: Space to play · Left / Right to stepExplore next problem

Worked example and algorithm walkthrough

Topic: Graphs · Traversal and connectivity

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

[
  [
    1,
    1,
    0
  ],
  [
    1,
    1,
    0
  ],
  [
    0,
    0,
    1
  ]
]

Execution steps

  1. Explore connected province

Computed output

2
JavaScript reference implementation
const solve = (a,s)=>{
  let seen=new Set,c=0;
  for(let i=0;
  i<a.length;
  i++)if(!seen.has(i)){
    c++;
    let q=[i];
    seen.add(i);
    while(q.length){
      let u=q.shift();
      for(let v=0;
      v<a.length;
      v++)if(a[u][v]&&!seen.has(v)){
        seen.add(v);
        q.push(v)
      }
      s("Explore connected province",{
        Matrix:a,Queue:q,Visited:[...seen],Count:[c]
      })
    }
  }
  return c
};

Continue learning

Practice related DSA questions in the same topic.