题解 | #疯牛病I#

疯牛病I

https://www.nowcoder.com/practice/2066902a557647ce8e85c9d2d5874086

import java.util.*;


public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     *
     * @param pasture int整型二维数组
     * @param k int整型
     * @return int整型
     */
    public int healthyCows (int[][] pasture, int k) {
        // write code here
        int m = pasture.length;
        int n = pasture[0].length;
        Queue<int[]> infectedQueue = new LinkedList<>();
        int healthyCount = 0;

        // Initialize the infected queue and count healthy cows
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (pasture[i][j] == 1) {
                    healthyCount++;
                } else if (pasture[i][j] == 2) {
                    infectedQueue.offer(new int[] {i, j});
                }
            }
        }

        int[][] directions = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};

        // Simulate the spread of disease using BFS
        while (!infectedQueue.isEmpty() && k > 0) {
            int size = infectedQueue.size();
            for (int i = 0; i < size; i++) {
                int[] current = infectedQueue.poll();
                for (int[] direction : directions) {
                    int newRow = current[0] + direction[0];
                    int newCol = current[1] + direction[1];
                    if (newRow >= 0 && newRow < m && newCol >= 0 && newCol < n &&
                            pasture[newRow][newCol] == 1) {
                        pasture[newRow][newCol] = 4; // Infect the healthy cow
                        infectedQueue.offer(new int[] {newRow, newCol});
                        healthyCount--;
                    }
                }
            }
            k--;
        }

        return healthyCount;
    }
}

全部评论

相关推荐

2024-12-08 18:59
东北大学 Java
Java抽象带篮子:外卖项目可以看看我的详细的外卖话术,里面还写了怎么描述项目,还为了提高含金量额外增加了很多技术亮点呢。另外我这边还有个7000多字的轮子项目话术,可以狠狠的速成,需要的似我
点赞 评论 收藏
分享
评论
点赞
收藏
分享
牛客网
牛客企业服务