Amazon Online Assessment (OA) - Treasure Island I
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 the top-left corner 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. 'X' will not be at the top-left corner.
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. The top-left corner is always safe.
Output the minimum number of steps to get to the treasure.
Input
The input consists of one 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 The starting point is always 'O', representing a safe area. There is no 'S' representing the starting point mentioned within the matrix description.
Output
Return the minimum number of steps for the route.
Examples
Example 1:
Input:
matrix = [ ['O', 'O', 'O', 'O'], ['D', 'O', 'D', 'O'], ['O', 'O', 'O', 'O'], ['X', 'D', 'D', 'O'], ]
Output: 5
Explanation:
Route is (0, 0), (0, 1), (1, 1), (2, 1), (2, 0), (3, 0). The minimum route takes 5 steps.
Try it yourself
Solution
Prerequisite: 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(start):
15 queue = deque([start])
16 r, c = start
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 return bfs((0, 0))
32
33if __name__ == "__main__":
34 rows = int(input())
35 matrix = [[x for x in input().split()] for _ in range(rows)]
36 result = routeStep(matrix)
37 print(result)
38
39