Advertisement
1sairandhri

treasure island

Apr 3rd, 2020
157
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.49 KB | None | 0 0
  1. You have a map that marks the location of a treasure island. Some of the map area has 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 a shortest route to the treasure island.
  2.  
  3. 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.
  4. def solution(m):
  5.     if len(m) == 0 or len(m[0]) == 0:
  6.         return -1  # impossible
  7.  
  8.     matrix = [row[:] for row in m]
  9.     nrow, ncol = len(matrix), len(matrix[0])
  10.  
  11.     q = deque([((0, 0), 0)])  # ((x, y), step)
  12.     matrix[0][0] = "D"
  13.     while q:
  14.         (x, y), step = q.popleft()
  15.  
  16.         for dx, dy in [[0, 1], [0, -1], [1, 0], [-1, 0]]:
  17.             if 0 <= x+dx < nrow and 0 <= y+dy < ncol:
  18.                 if matrix[x+dx][y+dy] == "X":
  19.                     return step+1
  20.                 elif matrix[x+dx][y+dy] == "O":
  21.                     # mark visited
  22.                     matrix[x + dx][y + dy] = "D"
  23.                     q.append(((x+dx, y+dy), step+1))
  24.  
  25.     return -1
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement