题解 | #疯牛病I#
疯牛病I
https://www.nowcoder.com/practice/2066902a557647ce8e85c9d2d5874086
题目考察的知识点是:
本题主要考察知识点是递归和回溯。
题目解答方法的文字分析:
遍历二维数组,找出元素值为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 count = 0;
// write code here
LinkedList<int[]>list = new LinkedList<>();
for (int i = 0; i < pasture.length; ++i) {
for (int j = 0; j < pasture[0].length; ++j) {
if (pasture[i][j] == 2)list.add(new int[] {i, j});
else if (pasture[i][j] == 1)count++;
}
}
int[][]directions = new int[][] {{0, -1}, {0, 1}, {1, 0}, {-1, 0}};
while (!list.isEmpty() && k > 0) {
int size = list.size();
for (int i = 0; i < size; ++i) {
int []temp = list.removeFirst();
for (int j = 0; j < 4; ++j) {
int newx = temp[0] + directions[j][0];
int newy = temp[1] + directions[j][1];
if (newx >= 0 && newx < pasture.length && newy >= 0 &&
newy < pasture[0].length) {
if (pasture[newx][newy] == 1) {
pasture[newx][newy] = 2;
count--;
list.add(new int[] {newx, newy});
}
}
}
}
--k;
}
return count;
}
}
#题解#
查看11道真题和解析