Problem · Breadth First Search

Grid Traversal (Infrastructure Automation Internship)

Learn this problem
HardSnowflake logoSnowflakeINTERNOA
See Snowflake hiring insights

Problem statement

Hackerland is represented by a grid with n rows and m columns. Empty cells are marked *, blocked cells are marked #, the start is marked S, and the destination is marked E.

A traveler may jump any positive integer length in one of four directions: up, down, left, or right. If a jump has length greater than 1, the next jump must continue in the same direction. A jump of length 1 releases this restriction, so the following jump may change direction. The last jump in the route must have length 1.

A jump may pass over blocked cells, but its starting and ending cells must be traversable. Determine the minimum number of jumps needed to reach E from S, or return -1 if no valid route exists.

Complete getMinJumps with String[] grid.

Returns: int, the minimum number of jumps, or -1 when the destination is unreachable.

Function

getMinJumps(grid: String[]) → int

Examples

Example 1

grid = ["S#", "#E"]return = -1

Neither adjacent landing cell is traversable, so the destination cannot be reached.

Example 2

grid = ["S******", "#######", "######*", "######E"]return = 4

An optimal route uses four jumps:

  1. Jump from (0, 0) to (0, 5).
  2. Continue right from (0, 5) to (0, 6).
  3. Jump down from (0, 6) to (2, 6).
  4. Continue down by one cell to (3, 6), the destination.

Example 3

grid = ["S****#", "**#***", "*****#", "*#*#**", "#****E"]return = 5

An optimal route is:

  1. Jump from (0, 0) to (0, 3).
  2. Continue right by one cell to (0, 4).
  3. Jump down to (3, 4).
  4. Continue down by one cell to (4, 4).
  5. Jump right by one cell to (4, 5).

The route uses 5 jumps.

Constraints

  • 2 ≤ n, m ≤ 100
  • Every row contains only *, #, S, and E.
  • The grid contains exactly one S and exactly one E.

More Snowflake problems

drafts saved locally
public int getMinJumps(String[] grid) {
  // write your code here
}
grid["S#", "#E"]
expected-1
checking account