Workspace Count Reachable Nodes
0d
Back to questionsDSA Visualizers: 388 Coding Questions

Count Reachable Nodes visualizer

Count distinct vertices reachable from target, including the start. Supply the directed graph as a flattened row-major 0/1 adjacency matrix.

EXECUTION LAB

Count distinct vertices reachable from target, including the start. Supply the directed graph as a flattened row-major 0/1 adjacency matrix.

Input and constraints
  • Use a square, flattened row-major adjacency matrix of zeros and ones, with a valid starting vertex as target.
  • Use at most 32 integers. Each numeric input is between -1000 and 1000.

Code inspector

def solve(values, target):
n = 1
while ((n * n) < len(values)):
n = (n + 1)
seen = [0] * (n)
queue = [0] * (n)
queue[0] = target
seen[target] = 1
head = 0
tail = 1
while (head < tail):
node = queue[head]
head = (head + 1)
neighbor = 0
while (neighbor < n):
if ((values[((node * n) + neighbor)] == 1) and (seen[neighbor] == 0)):
seen[neighbor] = 1
queue[tail] = neighbor
tail = (tail + 1)
neighbor = (neighbor + 1)
return tail

Visualizer

Step 1 of 13
0visited12

Dequeue the next frontier vertex

Dequeue the next frontier vertex.

Variable watch

head 0tail 1seen [1,0,0]queue [0,0,0]

Step explanation

Dequeue the next frontier vertex.

comparisons 4reads 0writes 2swaps 0recursiveCalls 0
Educational simulation · O(V²) for the matrix time · O(V) space

Worked explanation

A message spreads through one circle of neighbours at a time.

Guided solution

Mark vertices on enqueue so several paths cannot enqueue the same vertex twice.

O(V²) for the matrix time · O(V) auxiliary space

Examples

Worked example · {"values":[0,1,1,0,0,1,0,0,0],"target":0} ⇒ 3

Edge case 1 · {"values":[0],"target":0} ⇒ 1

Edge case 2 · {"values":[0,0,0,0],"target":1} ⇒ 1

Progressive hints

Hint 1A message spreads through one circle of neighbours at a time.
Hint 2Mark vertices on enqueue so several paths cannot enqueue the same vertex twice.
Hint 3Step through the worked example and inspect the highlighted variables before each update.

Common mistake

Waiting until dequeue to mark a vertex can create duplicate frontier entries.

Interview follow-up

How would an adjacency list change work on a sparse graph?

Continue learning

Practice related DSA questions in the same topic.