TopcoderArchive
Archive
Algorithm problem

TreasureMap

Problem statement, definition, constraints, and public examples.

Problem Statement

Robert has come into possession of an ancient treasure map. The map depicts a rectangular cave, and is divided into square cells representing the cave's chambers. The treasure is located in one of the chambers. Each of the remaining cells contains an arrow that is supposed to show the direction from that chamber to the treasure.

Robert will enter the cave in the upper left corner of the map. He intends to follow the arrows on the map and find the treasure. After looking at the arrows for a while, he got confused and is no longer sure that he will reach the treasure: it is possible that the arrows will lead him off the map, or have him going in circles. He wants to know if he will reach the treasure and, if yes, how many chambers he will go through before reaching it.

You will be given a String[] cave representing Robert's map. The treasure is marked with a period ('.'), while arrows are represented with characters '<', '>', '^' and 'v'. The chamber Robert first enters (the upper-left corner of the map) is character (0, 0) in cave. Return the number of chambers Robert goes through before finding the treasure. If he never reaches the treasure, return -1.

Definition

Class:
TreasureMap
Method:
howManyChambers
Parameters:
String[]
Returns:
int
Method signature:
int howManyChambers(String[] cave)
(be sure your method is public)

Constraints

  • cave will contain between 1 and 50 elements, inclusive.
  • Each element of cave will contain between 1 and 50 characters, inclusive.
  • Each element of cave will contain the same number of characters.
  • Each character in cave will be one of '.' (ASCII value 46), '<' (ASCII value 60), '>' (ASCII value 62), '^' (ASCII value 94) and 'v' (ASCII value 118).
  • There will be exactly one period character in cave.

Examples

  1. { ">v^",
      "v>v",
      "<<." }
    Returns: 4
    Robert walks right, down, right and then down to reach the treasure.
  2. { ">>>>^",
      "vvvvv",
      "vvv.v" }
    Returns: -1
    Here the arrows lead Robert along the top edge of the map and then out of the cave.
  3. { ">>v",
      ">^<",
      "vvv",
      ".vv" }
    Returns: -1
    Robert moves right and enters a loop he can't get out of.
  4. { ".v^<<",
      "v><><",
      "^^^<>",
      "vv^<>",
      "^v<>v" }
    Returns: 0
  5. { ">>>v<^<vv^",
      "<v>vv^v^^v",
      "^^<v>^>vv^",
      "^<vv>.v<<>",
      "^v^v<^<<<^",
      "^vvvv^^^<v",
      "^vv>>>>^>v",
      ">>v>vv>>>^",
      "<<><><><<>",
      "^^<>v<><v^" }
    Returns: 18
Back to all problems