新冠疫情爆发,Drizzle 想知道假如在一个区域内分布着正常人和感染者,感染者每天会感染附近(上下左右)的正常人,多少天内所有人都被感染,求出最少天数days,如果不会被全部感染则输出victory。
要求:
输入:第一行输入两个整数m,n表示地图区域的行列,随后的m行输入n个数字表示地图中的人员布局(0表示没人,1表示正常人,2表示感染者)。
输出:假如所有人被感染输出全部人员都被感染的天数num,否则输出victory。
示例:
输入:
3 3
2 1 1
1 1 0
0 1 1
输出:
4
import java.util.*;
class point {
int x;
int y;
public point(int x, int y) {
this.x = x;
this.y = y;
}
public String toString() {
return x + " " + y;
}
}
public class Main {
static int days = 0;
static Queue<point> que = new LinkedList<point>();
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int sum = 0;
int m = in.nextInt();
int n = in.nextInt();
int[][] nums = new int[m][n];
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
nums[i][j] = in.nextInt();
if (nums[i][j] == 1) {
sum++;
}
if (nums[i][j] == 2) {
que.add(new point(i, j));
}
}
}
while (true) {
boolean flag = true;
int size = que.size();
for (int i = 0; i < size; i++) {
int x = que.peek().x;
int y = que.peek().y;
if (x + 1 < m && nums[x + 1][y] == 1) {
nums[x + 1][y] = 2;
que.add(new point(x + 1, y));
sum--;
flag = false;
}
if (x - 1 >= 0 && nums[x - 1][y] == 1) {
nums[x - 1][y] = 2;
que.add(new point(x - 1, y));
sum--;
flag = false;
}
if (y + 1 < n && nums[x][y + 1] == 1) {
nums[x][y + 1] = 2;
que.add(new point(x, y + 1));
sum--;
flag = false;
}
if (y - 1 >= 0 && nums[x][y - 1] == 1) {
nums[x][y - 1] = 2;
que.add(new point(x, y - 1));
sum--;
flag = false;
}
que.remove();
}
if (flag == true && sum != 0) {
System.out.println("victory");
return;
}
days++;
if (sum == 0) {
System.out.println(days);
return;
}
}
}
}