腐烂的橘子
题目描述
在给定的 m ∗ n m * n m∗n 网格 grid 中,每个单元格可以有以下三个值之一:
值 0 代表空单元格;
值 1 代表新鲜橘子;
值 2 代表腐烂的橘子。
每分钟,腐烂的橘子 周围 4 个方向上相邻 的新鲜橘子都会腐烂。
返回 直到单元格中没有新鲜橘子为止所必须经过的最小分钟数。如果不可能,返回 -1 。
示例 1:
输入格式
第一行一个数 t t t表示询问组数
第二行开始每组数先是 m , n m,n m,n( m , n m,n m,n代表网格的长和宽),接着$ m 行 行 行n$列数,空格隔开。
输出格式
t个数,表示最小分钟数,每个数占一行。
样例 #1
样例输入 #1
2
3 3
2 1 1
1 1 0
0 1 1
3 3
2 1 1
0 1 1
1 0 1
样例输出 #1
4
-1
提示
1 < = t < = 20 1<=t<=20 1<=t<=20
1 < = m , n < = 1000 1 <= m, n <= 1000 1<=m,n<=1000
代码
#include<bits/stdc++.h>
using namespace std;
const int N = 1e3 + 5;
const int M = 1e3 + 5;
int grid[M][N], st[M][N]; //记录当前坐标橘子被腐烂的时间
int cnt, m, n, t; //维护新鲜橘子数量
int dx[4] = {-1, 1, 0, 0}, dy[4] = {0, 0, -1, 1};
struct data {
int f, s;
};
queue<data> q;
int bfs() {
int ans = 0; //记录最久被污染橘子的污染时间
//开始 bfs
while (!q.empty()) {
auto t = q.front();
q.pop();
int x = t.f, y = t.s; //腐烂源橘子坐标
for (int i = 0; i < 4; i ++) {
int xx = x + dx[i], yy = y + dy[i]; //下一步坐标
if (xx >= m || xx < 0 || yy >= n || yy < 0 || st[xx][yy] != 0 || !grid[xx][yy]) {
continue; //越界或遇到空
}
if (grid[xx][yy] == 1) {
grid[xx][yy] = 2; //别忘了更新橘子状态为已污染,否则死循环
st[xx][yy] = st[x][y] + 1; //新鲜橘子被污染,被污染时间设置为污染源橘子时间 + 1.
q.push({xx, yy});
cnt--; //新鲜橘子少了
ans = st[xx][yy];
if (cnt == 0) break; //橘子已经全部被污染,返回当前记录橘子最长被污染时间的值 ans
}
}
}
return cnt == 0 ? ans : -1; //cnt 不为 0,橘子未被全部污染
}
int main() {
cin >> t;
while (t--) {
memset(st, 0, sizeof(st));
memset(grid, 0, sizeof(grid));
cnt = 0;
scanf("%d%d", &m, &n);
for (int i = 0; i < m; i++)
for (int j = 0; j < n; j++) {
scanf("%d", &grid[i][j]);
if (grid[i][j] == 2) {
st[i][j] = 0; //初始腐烂橘子
q.push({i, j});
} else if (grid[i][j] == 1) cnt++; //新鲜橘子数++
}
cout << bfs() << endl;
}
return 0;
}