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?- A. 1
- B. 2
- C. 3
- 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
- Problem: Junctions 1..6 form a precedence graph with edges 4 to 1, 3 to 1, 2 to 5 (an edge a to b means a must come before b). Kahn's…
- Problem: Kruskal's algorithm with union-find is run on 5 nodes (0..4) with weighted edges (4,0,1), (1,1,2), (3,0,2), (2,2,3), (7,3,4)…
- Problem: Count the subsets (including the empty subset) of {1, 2, 3, 4, 5, 6} whose sum is divisible by 3. python a = [1, 2, 3, 4, 5, 6]…
- Problem: How many integers x with 1 <= x <= 100 have no two adjacent equal decimal digits? Use the rule that a one-digit number always…
- Problem: What is the sum of all divisors of 360 = 2^3 3^2 5?
- Problem: Find the smallest positive x satisfying x ≡ 2 (mod 3), x ≡ 3 (mod 5) and x ≡ 2 (mod 7).