知识点:二维数组,广度优先遍历
遍历二维数组,找出元素值为2的所有位置,将其加入到队列中,每过一分钟,k-1,将队列中的所有元素出队,判断四个方向中是否有值为1的元素,将其更新为2,并入队,重复以上操作,直至k=0,最后,遍历一遍数组,得到所有值为1的元素个数,即为答案。
Java题解如下
import java.util.*;
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param pasture int整型二维数组
* @param k int整型
* @return int整型
*/
public int healthyCows (int[][] pasture, int k) {
// write code here
int[][] dirs = new int[][]{{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
int m = pasture.length;
int n = pasture[0].length;
Queue<int[]> queue = new ArrayDeque<>();
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});
}
}
}
while(k > 0) {
k--;
int size = queue.size();
for(int i = 0; i < size; i++) {
int[] poll = queue.poll();
for(int[] dir: dirs) {
int x = poll[0] + dir[0];
int y = poll[1] + dir[1];
if(x >= 0 && x < m && y >= 0 && y < n && pasture[x][y] == 1) {
pasture[x][y] = 2;
queue.offer(new int[]{x, y});
}
}
}
}
int count = 0;
for(int i = 0; i < m; i++) {
for(int j = 0; j < n; j++) {
if(pasture[i][j] == 1) {
count++;
}
}
}
return count;
}
}



京公网安备 11010502036488号