Amazon Online Assessment (OA) - Treasure Island II
You have a map that marks the location of a treasure island. Some of the map areas have jagged rocks and dangerous reefs. Other areas are safe to sail in.
There are other explorers trying to find the treasure. So you must figure out the shortest route to the treasure island.
Assume the map area is a two-dimensional grid, represented by a matrix of characters.
You must start from one of the starting points (marked as 'S') of the map and can move one block up, down, left, or right at a time.
The treasure island is marked as 'X' in a block of the matrix.
Any block with dangerous rocks or reefs will be marked as 'D'. You must not enter dangerous blocks. You cannot leave the map area.
Other areas 'O' are safe to sail in.
Output the minimum number of steps to get to the treasure.
Input
The input consists of an argument:
matrix
: a 2D string array where X
represents the treasure island, D
represents dangerous rocks or reefs, O
represents safe to sail in areas, and 'S' represents the starting point
Output
Return a minimum number of steps for the route
Examples
Example 1:
Input:
matrix = [ [‘S’, ‘O’, ‘O’, 'S', ‘S’], [‘D’, ‘O’, ‘D’, ‘O’, ‘D’], [‘O’, ‘O’, ‘O’, ‘O’, ‘X’], [‘X’, ‘D’, ‘D’, ‘O’, ‘O’], [‘X', ‘D’, ‘D’, ‘D’, ‘O’], ]
Output: 3
Explanation:
You can start from (0,0), (0, 3), or (0, 4). The treasure locations are (2, 4), (3, 0), and (4, 0). Here, the shortest route is (0, 3), (1, 3), (2, 3), (2, 4).
Try it yourself
Solution
Prereq: Number of Islands
1def routeStep(matrix: list[list[str]]) -> int:
2 from collections import deque
3 num_rows = len(matrix)
4 num_cols = len(matrix[0])
5
6 def get_neighbors(coord):
7 row, col = coord
8 for dx, dy in [(-1, 0), (0, -1), (1, 0), (0, 1)]:
9 r = row + dx
10 c = col + dy
11 if 0 <= r < num_rows and 0 <= c < num_cols and matrix[r][c] != 'D':
12 yield (r, c)
13
14 def bfs(starts):
15 queue = deque(starts)
16 for r, c in starts:
17 matrix[r][c] = ' '
18 dist = 0
19 while len(queue) > 0:
20 dist += 1
21 n = len(queue)
22 for _ in range(n):
23 node = queue.popleft()
24 for r, c in get_neighbors(node):
25 if matrix[r][c] == 'X':
26 return dist
27 if matrix[r][c] == ' ':
28 continue
29 queue.append((r, c))
30 matrix[r][c] = ' '
31
32 return bfs([
33 (r, c)
34 for r, row in enumerate(matrix)
35 for c, v in enumerate(row)
36 if v == 'S'
37 ])
38
39if __name__ == "__main__":
40 rows = int(input())
41 matrix = [[x for x in input().split()] for _ in range(rows)]
42 result = routeStep(matrix)
43 print(result)
44
45