FastPrepShortest Path from Car to Oasis

Shortest Path from Car to Oasis

Bloomberg LP logoBloomberg LP● MediumNEW GRADONSITE INTERVIEW
Learn

Problem statement

A rectangular desert grid contains exactly one car C, exactly one oasis O, open ground ., and blocked cells #.

From an open cell, the car may move one cell up, down, left, or right. It may not leave the grid or enter a blocked cell.

Return the minimum number of moves needed to reach the oasis. Return -1 if the oasis is unreachable.

Function

shortestPathToOasis(grid: String[]) → int

Examples

Example 1

grid = ["C..",".#.","..O"]return = 4

One shortest path uses four orthogonal moves around the blocked center cell.

Example 2

grid = ["C#O","###","..."]return = -1

Blocked cells separate the car from the oasis.

Example 3

grid = ["CO"]return = 1

The oasis is directly adjacent to the car.

Constraints

  • 1 <= grid.length <= 200.
  • 1 <= grid[i].length <= 200, and every row has the same length.
  • Every cell is one of C, O, ., or #.
  • The grid contains exactly one C and exactly one O.

More Bloomberg LP problems

See Bloomberg LP hiring insights
public int shortestPathToOasis(String[] grid) {
    // Write your code here.
}
grid["C..",".#.","..O"]
expected4
Checking account…