Full answer
Problem
Part 1: given a directed graph whose edge weights are 0 or 1, return the shortest distance from a source to every node.
Part 2: each cell of an R x C grid holds an arrow (1 right, 2 left, 3 down, 4 up). Moving along a cell's arrow is free; changing the arrow costs 1. Return the minimum cost to reach the bottom-right cell from the top-left.
Example: for the grid [[1,1,1,1],[2,2,2,2],[1,1,1,1],[2,2,2,2]] the answer is 3. For [[1,1,3],[3,2,2],[1,1,4]] the answer is 0, because the arrows already lead to the end.
Constraints: up to 10^5 nodes or 100 x 100 cells.
Brute force
Run Dijkstra with a heap: correct, O((V + E) log V). Plain BFS is wrong because it counts every edge as 1.
Optimal approach
Initialise dist[src] = 0, deque [src]. Pop from the front. For each edge (u, v, w), if dist[u] + w < dist[v], update it and push v to the front when w == 0, to the back when w == 1.
For the grid, nodes are cells; from each cell, all 4 moves are edges, with weight 0 if the move matches the arrow and 1 otherwise.
Why it works
The deque always holds nodes whose distance is d at the front and d + 1 at the back, in that order. A 0-edge produces another distance d node, which belongs at the front; a 1-edge produces d + 1, which belongs at the back. So nodes come off the front in non-decreasing distance order, the same order Dijkstra would use, without paying for a heap. A node may be pushed more than once, but only when its distance strictly improves, and the cross-check against heap Dijkstra confirms the distances.
Complexity
O(V + E) time and O(V) space. On the grid: O(R * C) because each cell has 4 edges.
Code
import heapq
import random
from collections import deque
def zero_one_bfs(n, edges, src):
"""Shortest paths when every weight is 0 or 1. Deque instead of heap: O(V + E).
0-weight edges go to the front (same distance), 1-weight edges to the back."""
adj = [[] for _ in range(n)]
for u, v, w in edges:
adj[u].append((v, w))
INF = float("inf")
dist = [INF] * n
dist[src] = 0
dq = deque([src])
while dq:
u = dq.popleft()
for v, w in adj[u]:
if dist[u] + w < dist[v]:
dist[v] = dist[u] + w
if w == 0:
dq.appendleft(v)
else:
dq.append(v)
return dist
def min_flips_grid(grid):
"""Each cell has an arrow 1=right 2=left 3=down 4=up. Following an arrow is free,
changing it costs 1. Minimum cost from top-left to bottom-right."""
rows, cols = len(grid), len(grid[0])
moves = {1: (0, 1), 2: (0, -1), 3: (1, 0), 4: (-1, 0)}
INF = float("inf")
dist = [[INF] * cols for _ in range(rows)]
dist[0][0] = 0
dq = deque([(0, 0)])
while dq:
r, c = dq.popleft()
for arrow, (dr, dc) in moves.items():
nr, nc = r + dr, c + dc
if 0 <= nr < rows and 0 <= nc < cols:
w = 0 if grid[r][c] == arrow else 1
if dist[r][c] + w < dist[nr][nc]:
dist[nr][nc] = dist[r][c] + w
(dq.appendleft if w == 0 else dq.append)((nr, nc))
return dist[-1][-1]
def dijkstra_ref(n, edges, src):
adj = [[] for _ in range(n)]
for u, v, w in edges:
adj[u].append((v, w))
dist = [float("inf")] * n
dist[src] = 0
h = [(0, src)]
while h:
d, u = heapq.heappop(h)
if d > dist[u]:
continue
for v, w in adj[u]:
if d + w < dist[v]:
dist[v] = d + w
heapq.heappush(h, (d + w, v))
return dist
if __name__ == "__main__":
edges = [(0, 1, 0), (1, 2, 1), (0, 2, 1), (2, 3, 0), (0, 3, 1), (3, 4, 1)]
assert zero_one_bfs(5, edges, 0) == [0, 0, 1, 1, 2]
assert min_flips_grid([[1, 1, 1, 1], [2, 2, 2, 2], [1, 1, 1, 1], [2, 2, 2, 2]]) == 3
assert min_flips_grid([[1, 1, 3], [3, 2, 2], [1, 1, 4]]) == 0
assert min_flips_grid([[4]]) == 0
rng = random.Random(74)
for _ in range(500):
n = rng.randint(1, 10)
es = [(rng.randrange(n), rng.randrange(n), rng.randint(0, 1)) for _ in range(rng.randint(0, 25))]
s = rng.randrange(n)
assert zero_one_bfs(n, es, s) == dijkstra_ref(n, es, s)
print("all tests passed")Save as b74_zero_one_bfs.py and run python3 b74_zero_one_bfs.py. It prints all tests passed (Python 3.13.5).
Edge cases
Single-cell grid (cost 0). Unreachable nodes stay infinity. All weights 0 (everything reachable costs 0). Weights other than 0 and 1 (use Dijkstra, or Dial's buckets for small integer weights).
Pattern
Deque-based shortest paths for binary weights. Variants: minimum walls to remove to reach a target, minimum obstacles in a grid, minimum edge reversals to make a path (original direction 0, reversed 1), and Dial's algorithm for small integer weights.
import heapq
import random
from collections import deque
def zero_one_bfs(n, edges, src):
"""Shortest paths when every weight is 0 or 1. Deque instead of heap: O(V + E).
0-weight edges go to the front (same distance), 1-weight edges to the back."""
adj = [[] for _ in range(n)]
for u, v, w in edges:
adj[u].append((v, w))
INF = float("inf")
dist = [INF] * n
dist[src] = 0
dq = deque([src])
while dq:
u = dq.popleft()
for v, w in adj[u]:
if dist[u] + w < dist[v]:
dist[v] = dist[u] + w
if w == 0:
dq.appendleft(v)
else:
dq.append(v)
return dist
def min_flips_grid(grid):
"""Each cell has an arrow 1=right 2=left 3=down 4=up. Following an arrow is free,
changing it costs 1. Minimum cost from top-left to bottom-right."""
rows, cols = len(grid), len(grid[0])
moves = {1: (0, 1), 2: (0, -1), 3: (1, 0), 4: (-1, 0)}
INF = float("inf")
dist = [[INF] * cols for _ in range(rows)]
dist[0][0] = 0
dq = deque([(0, 0)])
while dq:
r, c = dq.popleft()
for arrow, (dr, dc) in moves.items():
nr, nc = r + dr, c + dc
if 0 <= nr < rows and 0 <= nc < cols:
w = 0 if grid[r][c] == arrow else 1
if dist[r][c] + w < dist[nr][nc]:
dist[nr][nc] = dist[r][c] + w
(dq.appendleft if w == 0 else dq.append)((nr, nc))
return dist[-1][-1]
def dijkstra_ref(n, edges, src):
adj = [[] for _ in range(n)]
for u, v, w in edges:
adj[u].append((v, w))
dist = [float("inf")] * n
dist[src] = 0
h = [(0, src)]
while h:
d, u = heapq.heappop(h)
if d > dist[u]:
continue
for v, w in adj[u]:
if d + w < dist[v]:
dist[v] = d + w
heapq.heappush(h, (d + w, v))
return dist
if __name__ == "__main__":
edges = [(0, 1, 0), (1, 2, 1), (0, 2, 1), (2, 3, 0), (0, 3, 1), (3, 4, 1)]
assert zero_one_bfs(5, edges, 0) == [0, 0, 1, 1, 2]
assert min_flips_grid([[1, 1, 1, 1], [2, 2, 2, 2], [1, 1, 1, 1], [2, 2, 2, 2]]) == 3
assert min_flips_grid([[1, 1, 3], [3, 2, 2], [1, 1, 4]]) == 0
assert min_flips_grid([[4]]) == 0
rng = random.Random(74)
for _ in range(500):
n = rng.randint(1, 10)
es = [(rng.randrange(n), rng.randrange(n), rng.randint(0, 1)) for _ in range(rng.randint(0, 25))]
s = rng.randrange(n)
assert zero_one_bfs(n, es, s) == dijkstra_ref(n, es, s)
print("all tests passed")Generic 0-1 BFS and the arrow-grid problem, cross-checked against heap Dijkstra on random 0/1-weighted graphs.
Complexity
Time: O(V + E). Space: O(V). Compared with Dijkstra, the log factor disappears because the deque replaces the heap.
By level
Fresher: Explains why plain BFS fails with 0-weight edges, then shows the deque rule on a small example. Models the arrow grid as a graph.
Mid: Implements 0-1 BFS, states the two-value invariant, and applies it to the grid and edge-reversal problems. Compares it with Dijkstra on cost.
Senior: Generalizes to Dial's algorithm with integer buckets and discusses when the log factor matters at scale. Recognizes binary-weight structure hidden in problems such as minimum obstacle removal.
Key points
- Only for weights 0 and 1
- 0-edge to the front, 1-edge to the back
- Deque holds at most two distance values
- O(V + E)
- Grid moves along the arrow are free
Common mistakes
- Using plain BFS and ignoring 0-edges
- Pushing 0-edges to the back
- Marking nodes visited on push and missing later improvements
- Using it with other weights
Follow-ups
- How would you handle weights 0, 1 and 2 (Dial's buckets)?
- How do you find the minimum number of edge reversals to reach a node?
- How would you reconstruct the path?
Tips
- State the deque invariant
- Contrast with Dijkstra's log factor
- Model the grid edges explicitly
Evaluation rubric
- Correct deque algorithm
- Correct grid modelling
- Correct complexity
- Explains the invariant