Continue learning
Practice related DSA questions in the same topic.
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.
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 tailDequeue the next frontier vertex.
Dequeue the next frontier vertex.
A message spreads through one circle of neighbours at a time.
Mark vertices on enqueue so several paths cannot enqueue the same vertex twice.
O(V²) for the matrix time · O(V) auxiliary space
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
Waiting until dequeue to mark a vertex can create duplicate frontier entries.
How would an adjacency list change work on a sparse graph?