Easiest to understand JS


  • 0
    A

    I personally haven't seen anything else this readable.

    const islandPerimeter = grid => {
        var perimeter = 0
        const isWater = val => !val
        const isLand = val => val === 1
        
        for (let y = 0; y < grid.length; y++) {
            for (let x = 0; x <= grid[y].length; x++) {
                var curr = grid[y][x]
                if (isLand(curr)) {
                    var top = grid[y - 1] && grid[y - 1][x]
                    var bottom = grid[y + 1] && grid[y + 1][x]
                    var left = grid[y][x - 1]
                    var right = grid[y][x + 1]
                    if (isWater(top)) perimeter++
                    if (isWater(bottom)) perimeter++
                    if (isWater(left)) perimeter++
                    if (isWater(right)) perimeter++
                }
            }
        }
        return perimeter
    };
    

Log in to reply
 

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