题解 | #疯牛病II#
疯牛病II
https://www.nowcoder.com/practice/2d5c96e452a949e09d98bb32aec3b61d
此题核心是在没传染的牛身边找被传染的牛
找到了就传染,没找到病牛但有健康牛则失败,没健康牛则成功
import java.util.*;
public class Solution {
static List<Integer> timeList = new ArrayList<>();
static int maxTime = -1;
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param pasture int整型二维数组
* @return int整型
*/
public int healthyCowsII (int[][] pasture) {
// write code here
trancefom(pasture, 0);
return maxTime;
}
public void trancefom(int[][] pasture, int index) {
int[][] newPasture = new int[pasture.length][pasture.length];
for(int i = 0; i < pasture.length; i ++) {
newPasture[i] = Arrays.copyOf(pasture[i], pasture.length);
}
// 查找健康牛有没有病牛在旁边
boolean hasTrance = false;
boolean haHealth = false;
for(int i = 0; i < newPasture.length; i ++) {
for(int k = 0; k < newPasture.length; k ++) {
if (newPasture[i][k] == 1) {
int X1 = i -1;
int X2 = i +1;
int Y1 = k -1;
int Y2 = k +1;
haHealth = true;
if (X1 >= 0) {
if (pasture[X1][k] == 2) {
newPasture[i][k] = 2;
hasTrance = true;
}
}
if (X2 < pasture.length) {
if (pasture[X2][k] == 2) {
newPasture[i][k] = 2;
hasTrance = true;
}
}
if (Y1 >= 0) {
if (pasture[i][Y1] == 2) {
newPasture[i][k] = 2;
hasTrance = true;
}
}
if (Y2 < pasture.length) {
if (newPasture[i][Y2] == 2) {
newPasture[i][k] = 2;
hasTrance = true;
}
}
}
}
}
// 则本轮结束
// 没有健康的牛
if (!haHealth) {
if (maxTime != -1) {
maxTime = maxTime > index ? index:maxTime;
} else {
maxTime = index;
}
return;
}
// 有健康牛但没有被传染
if (haHealth && !hasTrance) {
return;
}
if (haHealth && hasTrance) {
trancefom(newPasture, index +1);
}
}
}
