Accepted Javascript solution


  • 0
    R

    Open to comments for improvement

    function islandPerimeter(grid, perimeter = 0) {
        if (!grid || !grid.length) {
            return perimeter;
        }
    
        for (let i = 0; i < grid.length; i++) {
            for (let j = 0; j < grid[ i ].length; j++) {
                if (grid[ i ][ j ] === 1) {
                    perimeter += leftSide(grid, i, j);
                    perimeter += topSide(grid, i, j);
                    perimeter += rightSide(grid, i, j);
                    perimeter += bottomSide(grid, i, j);
                }
            }
        }
    
        return perimeter;
    }
    
    function leftSide(grid, i, j) {
        if (!grid[ i ] || !grid[ i ][ j - 1 ]) {
            return 1;
        }
    
        return 0;
    }
    
    function topSide(grid, i, j) {
        if (!grid[ i - 1 ] || !grid[ i - 1 ][ j ]) {
            return 1;
        }
    
        return 0;
    }
    
    function rightSide(grid, i, j) {
        if (!grid[ i ] || !grid[ i ][ j + 1 ]) {
            return 1;
        }
    
        return 0;
    }
    
    function bottomSide(grid, i, j) {
        if (!grid[ i + 1 ] || !grid[ i + 1 ][ j ]) {
            return 1;
        }
    
        return 0;
    }
    

Log in to reply
 

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