BFS-2.1 completed#617
Conversation
|
Strengths:
Areas for Improvement:
Suggested Changes:
Example correction (based on reference solution): class Solution {
public:
int orangesRotting(vector<vector<int>>& grid) {
int m = grid.size(), n = grid[0].size();
int fresh = 0;
queue<pair<int, int>> q;
vector<vector<int>> dirs = {{1,0}, {-1,0}, {0,1}, {0,-1}};
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (grid[i][j] == 1) fresh++;
else if (grid[i][j] == 2) q.push({i, j});
}
}
if (fresh == 0) return 0;
int time = 0;
while (!q.empty()) {
int size = q.size();
time++;
for (int i = 0; i < size; i++) {
auto [x, y] = q.front(); q.pop();
for (auto& dir : dirs) {
int nx = x + dir[0], ny = y + dir[1];
if (nx >= 0 && ny >= 0 && nx < m && ny < n && grid[nx][ny] == 1) {
grid[nx][ny] = 2;
fresh--;
q.push({nx, ny});
if (fresh == 0) return time;
}
}
}
}
return -1;
}
}; |
|
Strengths:
Areas for improvement:
Here is a corrected version of your code without the sets: Note: The above code increments time after processing each level. However, the first level (initial rotten oranges) is processed without incrementing time? Actually, we start with time=0, and after processing the first level we increment time to 1. But the initial rotten oranges are at time 0. So when we process the initial queue, we are going to infect neighbors at time 1. This is correct. But in the code above, we return time when fresh becomes zero after processing a level. So for the first infection, we return time=1. However, in the reference solution, time is initialized to 0 and then incremented at the beginning of the while loop. Then it returns time when fresh becomes zero. This is equivalent. But in your original code, you started time at -1 and then incremented at the beginning of the while loop. Then after processing all, you returned time. This would be off by one. |
No description provided.