题解 | #疯牛病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 类:用于存储键值对,这里用于存储牛在牧场中的位置。
全部评论

相关推荐

zYvv:双一流加大加粗再标红,然后广投。主要是获奖荣誉不够,建议开始不用追求大厂,去别的厂子刷下实习。
点赞 评论 收藏
分享
07-02 10:39
门头沟学院 Java
Steven267:说点真实的,都要秋招了,还没有实习,早干嘛去了,本来学历就差,现在知道急了,而且你这个简历完全可以写成一页,劣势太大了,建议转测试
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务