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