26 · Graphs: BFS & DFS

#1730 Shortest Path to Get Food

frequently reported atBloomberg

the problem

In plain words

You're hungry, standing on a char grid. '*' is you (exactly one), '#' is a food cell (there may be several, or none), 'O' is free space and 'X' is an obstacle. Each move goes up, down, left or right onto a non-'X' cell. Return the fewest moves to reach any food cell, or -1 if you can't reach food.

in grid = [[X,X,X,X,X,X],[X,*,O,O,O,X],[X,O,O,#,O,X],[X,X,X,X,X,X]]

out 3

Right, right, down — or down, right, right.

in grid = [[X,X,X,X,X],[X,*,X,O,X],[X,O,X,#,X],[X,X,X,X,X]]

out -1

A column of X splits you from the food.

in grid = [[X,X,X,X,X,X,X,X],[X,*,O,X,O,#,O,X],[X,O,O,X,O,O,X,X],[X,O,O,O,O,#,O,X],[X,X,X,X,X,X,X,X]]

out 6

The food in row 3 is nearer than the one in row 1.

in grid = [[X,X,X,X,X],[X,*,X,O,X],[X,O,X,#,X],[O,O,O,O,O]]

out 5

Down, down, right, right, up — around the wall through the open bottom row.

  • 1 ≤ m, n ≤ 200
  • grid[i][j] is '*', 'X', 'O' or '#'
  • Exactly one '*'

your turn

Try it before you peek

Read the examples, say the brute force out loud, then write code right here. Stuck for 20 minutes? Open one hint at a time.

This one is LeetCode Premium. You don't need a subscription: solve it right here. The free alternative linked above is the closest free practice; its label says how close it is.

Solve it in the browser

LeetCode-style: complete the class. Compiled by the real javac (Java 17) and judged right here — nothing is sent anywhere.

    Solutions are hidden so you can try first. Even 20 minutes of real effort makes the answer stick far better than reading it.

    Marking the problem solved, or opening every hint, also shows it.

    practise next

    Similar problems

    1. #1091
    2. #286
      Walls and Gates
      Mediumin GraphsLeetCode Premium
    3. #542
      01 Matrix
      Mediumin Graphs