Data Structures & AlgorithmsVery hardCodeforces Div2 D · 0-1 BFS

Problem: A grid of 0/1 costs (a cell costs its value when you enter it) is solved by 0-1 BFS from the top-left cell to the bottom-right cell, using a deque that pushes 0-cost moves to the front. Grid: [[0,1,1],[1,0,1],[1,1,0]]. What is the minimum total cost of entering cells from (0,0) to (2,2)?

Problem: A grid of 0/1 costs (a cell costs its value when you enter it) is solved by 0-1 BFS from the top-left cell to the bottom-right cell, using a deque that pushes 0-cost moves to the front. Grid: [[0,1,1],[1,0,1],[1,1,0]]. What is the minimum total cost of entering cells from (0,0) to (2,2)?
from collections import deque
def solve(grid):
    n, m = len(grid), len(grid[0])
    INF = 10 ** 9
    d = [[INF] * m for _ in range(n)]
    d[0][0] = 0
    dq = deque([(0, 0)])
    while dq:
        x, y = dq.popleft()
        for dx, dy in ((1, 0), (-1, 0), (0, 1), (0, -1)):
            nx, ny = x + dx, y + dy
            if 0 <= nx < n and 0 <= ny < m:
                w = grid[nx][ny]
                if d[x][y] + w < d[nx][ny]:
                    d[nx][ny] = d[x][y] + w
                    if w == 0:
                        dq.appendleft((nx, ny))
                    else:
                        dq.append((nx, ny))
    return d[n - 1][m - 1]
print(solve([[0, 1, 1], [1, 0, 1], [1, 1, 0]]))
What is printed?
  1. A. 1
  2. B. 2
  3. C. 3
  4. D. 4

Correct answer: B. 2

The path (0,0) to (1,0) to (1,1) to (2,1) to (2,2) pays 1 + 0 + 1 + 0 = 2 under the cells' costs in the code, and the 0-cells are settled first by the deque order. The code's output is the minimum, which the BFS relies on.

More Coding Interview Problems questions

Exams that ask this topic