编辑代码

/**
 * @param {number[][]} grid
 * @return {number}
 */
var maxAreaOfIsland = function (grid) {
    const col = grid.length, row = grid[0].length;
    let count = 0;
    for (let i = 0; i < col; i++) {
        for (let j = 0; j < row; j++) {
            count = Math.max(count, func(i, j))
        }
    }

    function func(x, y) {
        let res = 0;
        if (grid[x][y] === 1) {
            // 本身
            res += 1;
            // 
            res += y-1 >= 0 ? func(x, y-1) : 0;
            // 
            res += y+1 <= row ? func(x, y+1) : 0;
            // 
            res += x-1 >= 0 ? func(x-1, y) : 0;
            // 
            res += x+1 <= col ? func(x+1, y) : 0;
            // 记录过的赋值0 避免重新计算
            grid[x][y] = 0;
        }
        return res;
    }
    return count;
};

const arr = [
    [0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0], 
    [0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0], 
    [0, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], 
    [0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 0, 0], 
    [0, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0], 
    [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], 
    [0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0], 
    [0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0]
]
const result = maxAreaOfIsland(arr)
console.log(result);
console.log(arr)