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.


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


Return a number of minimum step for route


Example 1:


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


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