输入:一个二维数组,每一个元素为0或者1
输出:最多有多少个1是连续的
连续的定义:上下左右相邻
const arr = [ [1, 0, 1, 1, 0], [1, 0, 0, 1, 1], [0, 0, 1, 0, 1], [1, 0, 1, 0, 1], [1, 0, 1, 1, 0], ]; function getNumber(arr, i, j) { let num = 1; arr[i][j] = 0; // console.log(i, j); // console.log(arr[i - 1]); if (arr[i - 1] && arr[i - 1][j]) { //上边 num += getNumber(arr, i - 1, j); } if (arr[i + 1] && arr[i + 1][j]) { //下边 num += getNumber(arr, i + 1, j); } if (arr[i][j - 1]) { //左边 num += getNumber(arr, i, j - 1); } if (arr[i][j + 1]) { //右边 num += getNumber(arr, i, j + 1); } return num } function getMax(arr) { let max = 0 for (let i = 0; i < arr.length; i++) { for (let j = 0; j < arr[i].length; j++) { const ele = arr[i][j] if (ele === 1) { const cur = getNumber(arr, i, j) cur > max && (max = cur) } } } return max } console.log(getMax(arr))
const arr = [ [1, 0, 1, 1, 0], [1, 0, 0, 1, 1], [0, 0, 1, 0, 1], [1, 0, 1, 0, 1], [1, 0, 1, 1, 0], ]; function getNumber(arr, i, j) { let num = 1; arr[i][j] = 0; // console.log(i, j); // console.log(arr[i - 1]); if (arr[i - 1] && arr[i - 1][j]) { //上边 num += getNumber(arr, i - 1, j); } if (arr[i + 1] && arr[i + 1][j]) { //下边 num += getNumber(arr, i + 1, j); } if (arr[i][j - 1]) { //左边 num += getNumber(arr, i, j - 1); } if (arr[i][j + 1]) { //右边 num += getNumber(arr, i, j + 1); } return num } function getMax(arr, x, y) { for (let i = 0; i < arr.length; i++) { for (let j = 0; j < arr[i].length; j++) { const ele = arr[i][j] if (ele === 1) { const cur = getNumber(arr, x, y) return cur; // cur > max && (max = cur) } } } return 0; } console.log(getMax(arr, 2, 2))