Java 题解 | #疯牛病II#
疯牛病II
https://www.nowcoder.com/practice/2d5c96e452a949e09d98bb32aec3b61d
import java.util.*;
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param pasture int整型二维数组
* @return int整型
*/
public int healthyCowsII (int[][] pasture) {
// write code here
int m = pasture.length;
int n = pasture[0].length;
Queue<int[]> queue = new LinkedList<>();
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
if (pasture[i][j] == 2) {
queue.offer(new int[] {i, j});
}
}
}
int[] mx = {0, 0, -1, 1};
int[] my = {1, -1, 0, 0};
while (!queue.isEmpty()) {
int x = queue.peek()[0];
int y = queue.peek()[1];
int time = pasture[x][y];
queue.poll();
for (int i = 0; i < 4; ++i) {
int move_x = x + mx[i];
int move_y = y + my[i];
if (move_x >= 0 && move_x < m && move_y >= 0 && move_y < n) {
if (pasture[move_x][move_y] == 1) {
pasture[move_x][move_y] = time + 1;
queue.offer(new int[] {move_x, move_y});
}
}
}
}
int ans = 0;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (pasture[i][j] == 1) {
return -1;
}
ans = Math.max(ans, pasture[i][j]);
}
}
return ans - 2;
}
}
Java语言。
该题考察的知识点包括:
- 队列(Queue)的使用
- 多维数组的遍历
- 条件判断和循环结构的运用
代码的解释如下:
- 遍历牧场,将感染源坐标(值为2)加入队列。
- 定义两个一维数组mx和my用于表示四个方向上的移动(上、下、左、右)。
- 进入循环,直到队列为空: 5. 取出队列的第一个元素,获取其坐标和对应的感染时间。 6. 对该元素进行上、下、左、右四个方向的移动,计算移动后的新坐标。 7. 如果移动后的坐标在牧场范围内,并且对应位置的值为1(健康的牛),则将其值更新为当前时间+1,并将新坐标加入队列。
- 循环结束后,遍历整个牧场,查找是否存在未感染的健康牛,如果有则返回-1。
- 否则,返回牧场中最大的感染时间-2作为结果。
查看14道真题和解析