题解 | #腐烂的苹果#
腐烂的苹果
https://www.nowcoder.com/practice/54ab9865ce7a45968b126d6968a77f34
class Solution { int dx[4] = {1, -1, 0, 0}; int dy[4] = {0, 0, 1, -1}; int row, col; public: /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param grid int整型vector<vector<>> * @return int整型 */ int rotApple(vector<vector<int> >& grid) { queue<pair<int, int>> q1; row = grid.size(), col = grid[0].size(); for (int i = 0; i < row; i++) { for (int j = 0; j < col; j++) { if (grid[i][j] == 2) { q1.push({i, j}); } } } int step = 0; while (q1.size()) { ++step; int sz = q1.size(); while (sz--) { auto [a, b] = q1.front(); q1.pop(); for (int i = 0; i < 4; i++) { int x = a + dx[i], y = b + dy[i]; if (x >= 0 && x < row && y >= 0 && y < col && grid[x][y] == 1) { grid[x][y] = grid[a][b]; q1.push({x, y}); } } } } for (int i = 0; i < row; i++) { for (int j = 0; j < col; j++) { if(grid[i][j] == 1) return -1; } } return step-1; } };