O(mn) Javascript solution


  • 1
    D
    /**
     * @param {number[][]} grid
     * @return {number}
     */
    var islandPerimeter = function(grid) {
        var edges = 0;
        grid.forEach((row, r) => {
            row.forEach((col, c) => {
                var left = grid[r][c-1] || 0;
                var right = grid[r][c+1] || 0;
                var top = (grid[r-1] || [])[c] || 0;
                var bottom = (grid[r-1] || [])[c] || 0;
                if (col === 1) {
                    edges += (4 - top - bottom - left - right)
                }
            })
        });
        return edges;
    };
    

  • 0
    M

    Very inspiring !
    Based on your solution, I replaced the 4 variables with an array.

    var islandPerimeter = function(grid) {
        let edges = 0;
        let dirs = [[-1, 0], [1, 0], [0, -1], [0, 1]];
        grid.forEach((row, i) => {
            row.forEach((v, j) => {
                if (v === 1) {
                    edges += 4;
                    dirs.forEach((dir) => {
                        edges -= (grid[i + dir[0]] || [])[j + dir[1]] || 0;
                    });
                }
            });
        });
        
        return edges;
    };
    

Log in to reply
 

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