Data Structures & AlgorithmsModerateTCS NQT · BFS warm-up
Problem: Starting at (0,0) in the grid below, how many cells are reachable by 4-directional moves through '.' cells? Run the BFS.
Problem: Starting at (0,0) in the grid below, how many cells are reachable by 4-directional moves through '.' cells? Run the BFS.
from collections import deque
g = ['..#', '.#.', '...']
seen = {(0, 0)}
q = deque([(0, 0)])
while q:
x, y = q.popleft()
for a, b in ((x + 1, y), (x - 1, y), (x, y + 1), (x, y - 1)):
if 0 <= a < 3 and 0 <= b < 3 and g[a][b] == '.' and (a, b) not in seen:
seen.add((a, b))
q.append((a, b))
print(len(seen))What is printed?- A. 9
- B. 5
- C. 7
- D. 6
Correct answer: C. 7
BFS from (0,0) reaches all 7 open cells: the walls at (0,2) and (1,1) do not cut off (1,2), which is entered from (2,2). Counting every cell including walls gives 9, reporting the BFS distance to the farthest cell gives 5, and allowing only right/down moves misses (1,2) and gives 6.
More Coding Interview Problems questions
- Problem: What is the minimum number of coins from {1, 5, 10, 25} summing to 63? Run the DP. python INF = 10 9 d = [0] + [INF] 63 for v in…
- Problem: Climbing stairs 0 to 5 with steps of 1 or 2, but stair 3 is broken and cannot be stood on. How many ways are there to reach stair…
- Problem: Is 'cdeab' a rotation of 'abcde'? Check with the substring test below. What is printed? python s, t = 'abcde', 'cdeab'…
- Problem: Find the minimum cost of a Hamiltonian tour starting and ending at city 0, with symmetric distances D =…
- Problem: How many ordered outcomes of three fair six-sided dice sum to 9? Run the code. python print(sum(1 for a in range(1, 7) for b in…
- Problem: What is the Pisano period of the Fibonacci sequence modulo 10 (the length after which (F(n), F(n+1)) mod 10 repeats (0, 1))? Run…