Shortest Path to Get Food
The problem
Given an m*n grid where each cell can be one of the following:
- ***** represents your starting position.There is exactly one ***** cell.
- # represents a food location.
- O represents an empty space, and you can move through these cells.
- X represents an obstacle, and you cannot pass through it. You can move up, down, left, or right and you must find the shortest path to reach a food cell (#). If there is no possible path, return -1.
Input: grid = [["X","X","X","X","X","X"],["X","*","O","O","O","X"],["X","O","O","#","O","X"],["X","X","X","X","X","X"]] Output: 3 Explanation: It takes 3 steps to reach the food.
Input: grid = [["X","X","X","X","X"],["X","*","X","O","X"],["X","O","X","#","X"],["X","X","X","X","X"]] Output: -1 Explanation: It is not possible to reach the food.
Input: 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"]]
- m == grid.length
- n == grid[i].length
- 1 <= m, n <= 200
- grid[row][col] is '', 'X', 'O', or '#'.
- The grid contains exactly one ''.
cpp
class Solution {
public:
int getFood(vector<vector<char>>& grid) {
//Your Code Goes Here
}
};java
class Solution {
public int getFood(char[][] grid) {
//Your Code Goes Here
}
}python
class Solution:
def getFood(self, grid):javascript
class Solution {
getFood(grid) {
}
}csharp
public class Solution
{
public int GetFood(char[][] grid)
{
}
}go
func getFood(grid [][]byte) int {
//your code goes here
}Stuck? Show a way to structure it+
- 01Locate the start cell.
- 02Enqueue it with distance zero and mark visited.
- 03Expand four valid non-obstacle neighbors.
- 04Return when a food cell is first reached.
- 05Return minus one if the queue empties.
Reference answer
Then expect these follow-ups
How would you return the actual path?
Tests: implementation extension
What changes with different movement costs?
Tests: constraint adaptation
Free to read · better with Enzo
Practice this out loud with Enzo
Enzo runs it as a mock interview, pushes back with follow-ups, and grades you on the rubric.
Next question