|
| 1 | +class Solution { |
| 2 | +public: |
| 3 | + int orangesRotting(vector<vector<int>>& grid) { |
| 4 | + int n = grid.size(); |
| 5 | + int m = grid[0].size(); |
| 6 | + |
| 7 | + // format: {{row, col}, time} |
| 8 | + queue<pair<pair<int, int>, int>> q; |
| 9 | + // visited array: copy of original grid |
| 10 | + vector<vector<int>> vis(n, vector<int>(m)); |
| 11 | + |
| 12 | + for (int i = 0; i < n; ++i) { |
| 13 | + for (int j = 0; j < m; ++j) { |
| 14 | + if (grid[i][j] == 2) { |
| 15 | + q.push({{i, j}, 0}); |
| 16 | + vis[i][j] = 2; // Use 2 to indicate a rotten orange |
| 17 | + } |
| 18 | + else { |
| 19 | + vis[i][j] = grid[i][j]; // Use the grid values directly |
| 20 | + } |
| 21 | + } |
| 22 | + } |
| 23 | + |
| 24 | + int time = 0; |
| 25 | + // 4-directional neighbours |
| 26 | + int dRow[] = {0, 1, 0, -1}; |
| 27 | + int dCol[] = {1, 0, -1, 0}; |
| 28 | + |
| 29 | + while (!q.empty()) { |
| 30 | + int r = q.front().first.first; |
| 31 | + int c = q.front().first.second; |
| 32 | + int t = q.front().second; |
| 33 | + time = max(time, t); |
| 34 | + q.pop(); |
| 35 | + |
| 36 | + for (int i = 0; i < 4; ++i) { |
| 37 | + int nrow = r + dRow[i]; |
| 38 | + int ncol = c + dCol[i]; |
| 39 | + |
| 40 | + if (nrow >= 0 && nrow < n && ncol >= 0 && ncol < m && vis[nrow][ncol] == 1 |
| 41 | + && grid[nrow][ncol] == 1) { |
| 42 | + q.push({{nrow, ncol}, t + 1}); |
| 43 | + vis[nrow][ncol] = 2; // Use 2 to indicate a rotten orange |
| 44 | + } |
| 45 | + } |
| 46 | + } |
| 47 | + |
| 48 | + // Check and return -1, if fresh oranges are left |
| 49 | + for (int i = 0; i < n; ++i) { |
| 50 | + for (int j = 0; j < m; ++j) { |
| 51 | + if (vis[i][j] == 1) { |
| 52 | + return -1; |
| 53 | + } |
| 54 | + } |
| 55 | + } |
| 56 | + |
| 57 | + return time; |
| 58 | + } |
| 59 | +}; |
0 commit comments