Workspace Breadth First Search
0d
DSA Problem Sheet

Breadth-First Search

Return the breadth-first visit order from start vertex target; inspect outgoing neighbours in ascending vertex order. Supply the directed graph as a flattened row-major 0/1 adjacency matrix.

EXECUTION LAB

Return the breadth-first visit order from start vertex target; inspect outgoing neighbours in ascending vertex order. 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)
out = [0] * (tail)
i = 0
while (i < tail):
out[i] = queue[i]
i = (i + 1)
return out

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

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

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?