import java.util.*; public class Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param pasture int整型二维数组 * @param k int整型 * @return int整型 */ public int healthyCows (int[][] pasture, int k) { // write code here Queue<int[]> queue = new LinkedList<>(); int n = pasture.length; int m = pasture[0].length; // 将初始时刻健康的牛加入队列 for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (pasture[i][j] == 2) { queue.offer(new int[] {i, j, k}); } } } int[] dx = {-1, 0, 1, 0}; int[] dy = {0, -1, 0, 1}; while (!queue.isEmpty()) { int[] curr = queue.poll(); int x = curr[0]; int y = curr[1]; int t = curr[2]; for (int i = 0; i < 4; i++) { int nx = x + dx[i]; int ny = y + dy[i]; if (nx >= 0 && ny >= 0 && nx < n && ny < m && pasture[nx][ny] == 1) { pasture[nx][ny] = 2; if (t - 1 > 0) { queue.offer(new int[] {nx, ny, t - 1}); } } } } int res = 0; // 统计剩余健康的牛的数量 for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (pasture[i][j] == 1) { res += 1; } } } return res; } }
Java编程语言。
该题考察的是广度优先搜索(BFS)和模拟算法。
遍历牧场中的健康牛,并将它们加入队列。然后,从队列中依次取出节点,并标记其周围的健康牛为感染状态,并将它们加入队列。最后,统计剩余的健康牛的数量并返回结果。