Approach
Breadth-first search
For Rotting Oranges, 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
- 41 lines of C++ from the credited upstream file 994-2.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 orangesRotting(vector<vector<int>>& 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 int countFresh = 0;8 queue<pair<int, int>> q;9 10 for (int i = 0; i < m; ++i)11 for (int j = 0; j < n; ++j)12 if (grid[i][j] == 1)13 ++countFresh;14 else if (grid[i][j] == 2)15 q.emplace(i, j);16 17 if (countFresh == 0)18 return 0;19 20 int step = 0;21 for (; !q.empty(); ++step)22 for (int sz = q.size(); sz > 0; --sz) {23 const auto [i, j] = q.front();24 q.pop();25 for (const auto& [dx, dy] : kDirs) {26 const int x = i + dx;27 const int y = j + dy;28 if (x < 0 || x == m || y < 0 || y == n)29 continue;30 if (grid[x][y] != 1)31 continue;32 grid[x][y] = 2; 33 q.emplace(x, y); 34 --countFresh; 35 }36 }37 38 return countFresh == 0 ? step - 1 : -1;39 }40};41