题解 | #疯牛病II# java
疯牛病II
https://www.nowcoder.com/practice/2d5c96e452a949e09d98bb32aec3b61d
import java.util.*;
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param pasture int整型二维数组
* @return int整型
*/
private ArrayList<Pair<Integer, Integer>> infected = new ArrayList<>();
public int healthyCowsII(int[][] pasture) {
int pre = 0;
pre = numHealthy(pasture);
int ans = 0;
while (pre > 0) {
oneMinute(pasture);
ans++;
int temp = numHealthy(pasture);
if (temp == pre) {
return -1;
}
pre = temp;
}
return ans;
}
private void oneMinute(int[][] pasture) {
int m = pasture.length;
int n = pasture[0].length;
infected.clear();
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (pasture[i][j] == 2) {
infected.add(new Pair<>(i, j));
}
}
}
for (Pair<Integer, Integer> pos : infected) {
int x = pos.getKey();
int y = pos.getValue();
if (x > 0 && pasture[x - 1][y] == 1) {
pasture[x - 1][y] = 2;
}
if (x < m - 1 && pasture[x + 1][y] == 1) {
pasture[x + 1][y] = 2;
}
if (y > 0 && pasture[x][y - 1] == 1) {
pasture[x][y - 1] = 2;
}
if (y < n - 1 && pasture[x][y + 1] == 1) {
pasture[x][y + 1] = 2;
}
}
}
private int numHealthy(int[][] pasture) {
int m = pasture.length;
int n = pasture[0].length;
int ans = 0;
for (int x = 0; x < m; x++) {
for (int y = 0; y < n; y++) {
if (pasture[x][y] == 1) {
ans++;
}
}
}
return ans;
}
private class Pair<K, V> {
private K key;
private V value;
public Pair(K key, V value) {
this.key = key;
this.value = value;
}
public K getKey() {
return key;
}
public V getValue() {
return value;
}
}
}
使用的编程语言是 Java。
该题考察的知识点包括数组遍历、条件判断、函数调用。
题目要求模拟牧场中健康牛和感染牛之间的传播过程,通过每分钟的更新来计算在多少分钟内可以使得健康牛全部感染,或者判断是否存在不可感染的情况。
代码的解释如下:
healthyCowsII方法:计算在牧场中感染传播过程中所需的时间,返回传播所需的分钟数。如果存在无法感染的情况,则返回 -1。oneMinute方法:模拟每分钟传播过程,更新感染状态。numHealthy方法:计算当前健康的牛的数量。- 内部的
Pair类:用于存储键值对,这里用于存储牛在牧场中的位置。
阿里云工作强度 705人发布