题解 | #疯牛病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 };