Javascript Solution


  • 0
    B
    var GRID_LEN = grid.length;
    var edge = 0;
    
    for(var i = 0; i < GRID_LEN; i++) {
        for(var j = 0; j < grid[i].length; j++) { 
            if(grid[i][j] === 1) edge += getedge(i, j);
        }
    }
    
    return edge;
    
    function getedge(x, y) {
        var sum = 4;
        if(x - 1 >= 0 && grid[x-1][y] === 1) sum--;
        if(y + 1 < grid[x].length && grid[x][y+1] === 1) sum--;
        if(x + 1 < GRID_LEN && grid[x+1][y] === 1) sum--;
        if(y - 1 >= 0 && grid[x][y-1] === 1) sum--;
        return sum;
    }

Log in to reply
 

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