Facebook Pixel

Amazon Online Assessment (OA) 2021 - Move The Obstacle | Demolition Robot | Robot Find Path

Solution

1from collections import deque
2
3def move_obstacle(lot: list[list[int]]) -> int:
4    num_rows = len(lot)
5    num_cols = len(lot[0])
6
7    def get_neighbors(coord):
8        row, col = coord
9        for dx, dy in [(-1, 0), (0, -1), (1, 0), (0, 1)]:
10            r = row + dx
11            c = col + dy
12            if 0 <= r < num_rows and 0 <= c < num_cols:
13                yield (r, c)
14
15    def bfs(start):
16        queue = deque([start])
17        r, c = start
18        lot[r][c] = 0
19        dist = 0
20        while len(queue) > 0:
21            dist += 1
22            n = len(queue)
23            for _ in range(n):
24                node = queue.popleft()
25                for r, c in get_neighbors(node):
26                    if lot[r][c] == 9:
27                        return dist
28                    if lot[r][c] == 0:
29                        continue
30                    queue.append((r, c))
31                    lot[r][c] = 0
32
33    return bfs((0, 0))
34
35if __name__ == "__main__":
36    lot = [[int(x) for x in input().split()] for _ in range(int(input()))]
37    res = move_obstacle(lot)
38    print(res)
39
Invest in Yourself
Your new job is waiting. 83% of people that complete the program get a job offer. Unlock unlimited access to all content and features.
Go Pro
Favorite (idle)