Approach
Breadth-first search
For Shortest Path to Get Food, the implementation explores reachable states in layers, which is the standard shape for unweighted shortest paths and minimum-step transitions.
- Model each valid configuration as a state and each legal move as an edge.
- Seed the queue with the starting state and mark it immediately.
- Expand each state once, recording distance or reachability for unseen neighbours.
Code notes
- 37 lines of Java from the credited upstream file 1730.java.
- The implementation visibly relies on sequence storage, work queue.
- 5 loop blocks detected.
Complexity
Verify that each state and transition is processed only a bounded number of times; that determines the traversal cost.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution {2 public int getFood(char[][] grid) {3 final int[][] DIRS = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};4 final int m = grid.length;5 final int n = grid[0].length;6 Queue<Pair<Integer, Integer>> q = new ArrayDeque<>(List.of(getStartLocation(grid)));7 8 for (int ans = 0; !q.isEmpty(); ++ans)9 for (int sz = q.size(); sz > 0; --sz) {10 final int i = q.peek().getKey();11 final int j = q.poll().getValue();12 for (int[] dir : DIRS) {13 final int x = i + dir[0];14 final int y = j + dir[1];15 if (x < 0 || x == m || y < 0 || y == n)16 continue;17 if (grid[x][y] == 'X')18 continue;19 if (grid[x][y] == '#')20 return ans + 1;21 q.add(new Pair<>(x, y));22 grid[x][y] = 'X'; 23 }24 }25 26 return -1;27 }28 29 private Pair<Integer, Integer> getStartLocation(char[][] grid) {30 for (int i = 0; i < grid.length; ++i)31 for (int j = 0; j < grid[0].length; ++j)32 if (grid[i][j] == '*')33 return new Pair<>(i, j);34 throw new IllegalArgumentException();35 }36}37