Clear and Easy Javascript solution - beat 98%


  • 0
    K

    For each land cell, its diameter is determined by the number of land cell neighbors it has.

    diameter = 4 - num of adjacent neighbors

    So the solution is very straightforward which is to traverse the entire grid and calculate the total diameter using this approach.

    Efficiency: O(n*m)

    var islandPerimeter = function(grid) {
        var diameter = 0;
        if(!grid || grid.length == 0) return 0;
        for(var m = 0; m < grid.length; m++){
            for(var n = 0; n < grid[m].length; n++){
                if(grid[m][n] == 1){
                    var left = n-1 < 0 ? 0 : grid[m][n-1];
                    var right = n + 1 >= grid[m].length ? 0 : grid[m][n+1];
                    var top = m - 1 < 0 ? 0 : grid[m-1][n];
                    var down = m + 1 >= grid.length ? 0 : grid[m+1][n];
                    var numOfAdj = right + left+top+down;
                    diameter += 4 - numOfAdj;
                }
                
            }
        }
        return diameter;
    };
    

Log in to reply
 

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