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
- 39 lines of C++ from the credited upstream file 1730.cpp.
- 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:3 int getFood(vector<vector<char>>& grid) {4 constexpr int kDirs[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};5 const int m = grid.size();6 const int n = grid[0].size();7 queue<pair<int, int>> q{{getStartLocation(grid)}};8 9 for (int ans = 0; !q.empty(); ++ans)10 for (int sz = q.size(); sz > 0; --sz) {11 const auto [i, j] = q.front();12 q.pop();13 for (const auto& [dx, dy] : kDirs) {14 const int x = i + dx;15 const int y = j + dy;16 if (x < 0 || x == m || y < 0 || y == n)17 continue;18 if (grid[x][y] == 'X')19 continue;20 if (grid[x][y] == '#')21 return ans + 1;22 q.emplace(x, y);23 grid[x][y] = 'X'; 24 }25 }26 27 return -1;28 }29 30 private:31 pair<int, int> getStartLocation(const vector<vector<char>>& grid) {32 for (int i = 0; i < grid.size(); ++i)33 for (int j = 0; j < grid[0].size(); ++j)34 if (grid[i][j] == '*')35 return {i, j};36 throw;37 }38};39