解题思路:将房间的布局情况存储在一个二维数组中,通过循环将每天的情况计算。
参考代码:
import java.util.Scanner;
class ArrayUtils {//用于避免数组溢出
public static boolean isInBounds(int row, int col, int numRows, int numCols) {
return row >= 0 && row < numRows && col >= 0 && col < numCols;
}
}
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
scanner.nextLine();
int flag[][] = new int[n][n];
for (int i = 0; i < n; i++) {
String str = scanner.nextLine();
for (int j = 0; j < n; j++) {
char ch = str.charAt(j);
if (ch == '@') flag[i][j] = 1;//感染为1
if (ch == '#') flag[i][j] = -1;//房间没人为-1
if (ch == '.') flag[i][j] = 0;//没被感染为0
}
}
int m = scanner.nextInt();
int ro[] = new int[m];
for (int i = 0; i < m; i++) {
ro[i] = 0;
}
for (int day = 0; day < m; day++) {
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (flag[i][j] == 1) {
ro[day]++;
}
}
}
// 复制当前状态用于下一轮判断,避免当天感染的位置立即影响其他位置
int[][] tempFlag = new int[n][n];
for (int i = 0; i < n; i++) {
System.arraycopy(flag[i], 0, tempFlag[i], 0, n);
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (tempFlag[i][j] == 1) {
if (ArrayUtils.isInBounds(i - 1, j, n, n) && tempFlag[i - 1][j] == 0) flag[i - 1][j] = 1;
if (ArrayUtils.isInBounds(i + 1, j, n, n) && tempFlag[i + 1][j] == 0) flag[i + 1][j] = 1;
if (ArrayUtils.isInBounds(i, j - 1, n, n) && tempFlag[i][j - 1] == 0) flag[i][j - 1] = 1;
if (ArrayUtils.isInBounds(i, j + 1, n, n) && tempFlag[i][j + 1] == 0) flag[i][j + 1] = 1;
}
}
}
}
System.out.println(ro[m - 1]);
}
}
0.0分
1 人评分