FastPrepShortest Path to Food with Directions

Shortest Path to Food with Directions

Zip logoZip● MediumNEW GRADPHONE SCREEN
Learn

Problem statement

You are given a rectangular grid containing exactly one starting cell * and exactly one food cell #. Open cells contain O, and blocked cells contain X.

From an open or starting cell, you may move one step up, down, left, or right without leaving the grid or entering a blocked cell. Return a shortest direction string that moves from * to #. Use the characters U, D, L, and R.

If several shortest strings exist, return the lexicographically smallest one. If the food cannot be reached, return an empty string.

Function

shortestFoodPath(grid: String[]) → String

Examples

Example 1

grid = ["XXXXXX","X*OOOX","XOX#OX","XOOOOX","XXXXXX"]return = "RRD"

Move right twice and then down. No route uses fewer than three steps.

Example 2

grid = ["X*O","OO#"]return = "DR"

Both DR and RD are shortest. DR is lexicographically smaller.

Example 3

grid = ["*X#"]return = ""

The blocked middle cell separates the start from the food.

Constraints

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

More Zip problems

See Zip hiring insights
public String shortestFoodPath(String[] grid) {
    // Write your code here.
}
grid["XXXXXX","X*OOOX","XOX#OX","XOOOOX","XXXXXX"]
expected"RRD"
Checking account…