827. Largest artificial island

Leetcode-cn.com/problems/ma…

  • Similar BFS
/**
 * @param {number[][]} grid
 * @return {number}
 */
var largestIsland = function (grid) {
    const width = grid.length
    const height = grid[0].length
    const dirctions = [[1, 0], [0, 1], [-1, 0], [0, -1]]
    let maxCount = 0
    for (let i = 0; i < grid.length; i++) {
        for (let j = 0; j < grid[i].length; j++) {
            if (grid[i][j] === 0) {
                let count = 0
                const copyGrid = JSON.parse(JSON.stringify(grid))
                const stack = [[i, j]]
                while (stack.length) {
                    const curr = stack.shift()
                    count++
                    for (let dir = 0; dir < dirctions.length; dir++) {
                        const nowDirX = curr[0] + dirctions[dir][0]
                        const nowDirY = curr[1] + dirctions[dir][1]
                        if (nowDirX >= 0 && nowDirX < width && nowDirY >= 0 && nowDirY < height && copyGrid[nowDirX][nowDirY] === 1) {
                            stack.push([nowDirX, nowDirY])
                            copyGrid[nowDirX][nowDirY] = -1
                        }

                    }

                }
                maxCount = Math.max(maxCount, count)
            }
        }
    }
    return maxCount === 0 ? width * height : maxCount
};
Copy the code