题解 | #疯牛病I#

疯牛病I

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

/**
 * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
 *
 * 
 * @param pasture int整型二维数组 
 * @param k int整型 
 * @return int整型
 */
function healthyCows(pasture, k) {
    // write code here
    let res = 0

    function check(arr, min) {
        if (min === 0) {

            arr.forEach((item) => item.forEach(item2 => {
                if (item2 === 1) {
                    res++
                }
            }))

            return
        }

        let row = arr.length - 1
        let col = arr[0].length - 1

        let indexArr = []
        
        for (let i = 0; i <= row; i++) {
            for (let j = 0; j <= col; j++) {
                if (arr[i][j] === 2) {
                    //上
                    if (i - 1 >= 0 && arr[i - 1][j] === 1) {
                        indexArr.push({ i: i - 1, j: j })
                    }

                    //下
                    if (i + 1 <= row && arr[i + 1][j] === 1) {
                        indexArr.push({ i: i + 1, j: j })
                    }

                    //左
                    if (j + 1 <= col && arr[i][j + 1] === 1) {
                        indexArr.push({ i: i, j: j + 1 })
                    }

                    //右
                    if (j - 1 >= 0 && arr[i][j - 1] === 1) {
                        indexArr.push({ i: i, j: j - 1 })
                    }
                }
            }
        }

        indexArr.forEach((item) => {
            arr[item.i][item.j] = 2
        })

        check(arr, min - 1)
    }
    console.log(pasture)
    check(pasture, k)

    return res
}



module.exports = {
    healthyCows: healthyCows
};

全部评论

相关推荐

不愿透露姓名的神秘牛友
07-02 18:35
简历上把1个月实习写成了3个月,会进行背调吗?
码农索隆:一个月有一个月的实习经历,三个月有三个月的实习经历
点赞 评论 收藏
分享
星辰再现:裁员给校招生腾地方
点赞 评论 收藏
分享
不要停下啊:大二打开牛客,你有机会开卷了,卷起来,去找课程学习,在牛客上看看大家面试笔试都需要会什么,岗位有什么需求就去学什么,努力的人就一定会有收获,这句话从来都经得起考验,像我现在大三了啥也不会,被迫强行考研,炼狱难度开局,啥也不会,找工作没希望了,考研有丝丝机会
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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