题解 | #疯牛病II#
疯牛病II
https://www.nowcoder.com/practice/2d5c96e452a949e09d98bb32aec3b61d
知识点:二维数组,广度优先搜索
遍历二维数组,找出元素值为2的所有位置,将其加入到队列中,每分钟将队列中的所有元素出队,判断四个方向中是否有值为1的元素,若有,则将其更新为2,并入队,也表示可以进行下一轮的搜索,重复以上操作,直至没有相邻的值为1的元素,最后,遍历一遍数组,若仍然存在值为1的元素,则返回-1,若不存在,则返回更新1所消耗的分钟数。
Java题解如下
import java.util.*; public class Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param pasture int整型二维数组 * @return int整型 */ public int healthyCowsII (int[][] pasture) { // 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}); } } } boolean flag = true; int time = 0; while(flag) { time++; flag = false; 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) { flag = true; pasture[x][y] = 2; queue.offer(new int[]{x, y}); } } } } for(int i = 0; i < m; i++) { for(int j = 0; j < n; j++) { if(pasture[i][j] == 1) { return -1; } } } return time - 1; } }