Count Reachable Nodes
Count distinct vertices reachable from target, including the start. Supply the directed graph as a flattened row-major 0/1 adjacency matrix.
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 tailVisualizer
Step 1 of 13Dequeue the next frontier vertex
Dequeue the next frontier vertex.
Variable watch
Step explanation
Dequeue the next frontier vertex.
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 1
A message spreads through one circle of neighbours at a time.Hint 2
Mark vertices on enqueue so several paths cannot enqueue the same vertex twice.Hint 3
Step 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?