ProgrammingHardTCS NQT · Accenture
What is printed?
What is printed?
from collections import deque
g = ['..#', '.##', '...']
def bfs(g):
R, C = len(g), len(g[0])
d = {(0, 0): 0}
q = deque([(0, 0)])
while q:
r, c = q.popleft()
for dr, dc in ((1, 0), (0, 1), (-1, 0), (0, -1)):
nr, nc = r + dr, c + dc
if 0 <= nr < R and 0 <= nc < C and g[nr][nc] == '.' and (nr, nc) not in d:
d[(nr, nc)] = d[(r, c)] + 1
q.append((nr, nc))
return d.get((R - 1, C - 1), -1)
print(bfs(g))- A. 3
- B. 5
- C. 4
- D. -1
Correct answer: C. 4
The only route runs down the left column and then right along the bottom row: (0,0) to (1,0) to (2,0) to (2,1) to (2,2), which is 4 steps. BFS finds the shortest one because each level is expanded before the next.
More Python Programming questions
- What is printed? python from functools import lrucache calls = 0 @lrucache(maxsize=None) def f(n): global calls calls += 1 if n < 2…
- What is printed? python def greedy(coins, amt): cnt = 0 for c in sorted(coins, reverse=True): cnt += amt // c amt %= c return cnt if amt…
- What is printed? python import bisect def lis(a): t = [] for x in a: i = bisect.bisectleft(t, x) if i == len(t): t.append(x) else: t[i] =…
- A list a is sorted in ascending order and may contain duplicates. Using bisectleft and bisectright from the bisect module, which…
- A Python list q holds n items. A loop repeatedly does x = q.pop(0) until q is empty. What is the total time cost of the loop in big-O terms?
- What is printed? python def rob(a): p, c = 0, 0 for x in a: p, c = c, max(c, p + x) return c print(rob([2, 7, 9, 3, 1]), rob([5]), rob([]))