Data Structures & AlgorithmsVery hardProduct company OA
0-1 BFS on a grid: stepping into '#' costs 1 (a wall to break), stepping onto '.' or 'T' costs 0. What is the minimum number of walls to break from S (top-left) to T (bottom-right), and how many walls are there?
0-1 BFS on a grid: stepping into '#' costs 1 (a wall to break), stepping onto '.' or 'T' costs 0. What is the minimum number of walls to break from S (top-left) to T (bottom-right), and how many walls are there?
from collections import deque
grid = ["S.#..",
"##.#.",
"..#.#",
".#..T"]
R, C = len(grid), len(grid[0])
dist = [[10**9] * C for _ in range(R)]
dq = deque([(0, 0)]); dist[0][0] = 0
while dq:
r, c = dq.popleft()
for dr, dc in ((1, 0), (-1, 0), (0, 1), (0, -1)):
nr, nc = r + dr, c + dc
if 0 <= nr < R and 0 <= nc < C:
w = 1 if grid[nr][nc] == "#" else 0
if dist[r][c] + w < dist[nr][nc]:
dist[nr][nc] = dist[r][c] + w
(dq.append if w else dq.appendleft)((nr, nc))
print(dist[3][4], sum(row.count("#") for row in grid))- A. 3 7
- B. 2 7
- C. 1 7
- D. 2 6
Correct answer: B. 2 7
Edges of weight 0 go to the FRONT of the deque and weight-1 edges to the back, so the deque always holds at most two distinct distances in order – Dijkstra's invariant in O(V + E) without a heap. Here S's free region and T's pocket {(2,3), (3,2), (3,3), T} are each sealed by walls, so at least 2 breaks are needed, and 2 suffice: break (0,2), walk free along the top row and down to (1,4), break (2,4) and step onto T. A plain BFS that counts steps instead of walls answers a different question.
Practise more Trees, Graphs, Recursion and Dynamic Programming questionsTrees, Graphs, Recursion and Dynamic Programming: notes and key points
More Trees, Graphs, Recursion and Dynamic Programming questions
- How many topological orders does this DAG on 6 vertices have? (counted by DP over bitmasks of already-placed vertices) python from…
- Fenwick (binary indexed) tree, 1-based, built by point additions; then a[3] += 10. What is printed (the internal array, a range sum and a…
- Segment tree for range-minimum with lazy range-add (the pending add stays at a node and is applied on the way up instead of being pushed…
- Four cities, symmetric distances; the bitmask DP (Held–Karp) is compared with the nearest-neighbour heuristic, both starting and ending at…
- Maximum-weight independent set on a tree (no two chosen nodes adjacent) by tree DP returning (best if u taken, best if u skipped)…
- BFS that also counts the number of shortest paths. What is printed (dist[7], ways[7], ways[6], ways[4])? python from collections import…