islandPerimeter with JavaScript


  • 0
    N
    /**
     * @param {number[][]} grid
     * @return {number}
     */
    const islandPerimeter = function(grid) {
        let island = 0;
        let neighbour = 0;
        let rows = grid.length;
        let coloumns = grid[0].length;
        
        for(let i = 0; i < rows; i += 1) {
            for(let j = 0; j < coloumns; j += 1) {
                if(grid[i][j] === 1) {
                    island += 1;
                
                    if(i < rows - 1 && grid[i + 1][j] === 1) {
                        neighbour += 1;
                    }
    
                    if(j < coloumns - 1 && grid[i][j + 1] === 1) {
                        neighbour += 1;
                    }
                }
            }
        }
        
        return 4 * island - 2 * neighbour;
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.