My go solution


  • 0
    I
    func islandPerimeter(grid [][]int) int {
        perimeter := 0 
        
        for i, _ := range grid { 
            for j := 0; j<len(grid[0]); j++ { 
                if grid[i][j] == 1 {
                    // If a land cell has n land neighbours it contributes 4 - n points to the perimeter
                    perimeter += (4 - landNeighbours(grid, i, j))
                }
            }
        }
        return perimeter
    }
    
    
    func landNeighbours(grid [][]int, i int, j int) int { 
        count := 0
        if i-1 >= 0 {
            count += grid[i-1][j]
        }
        if i+1 < len(grid) {
            count += grid[i+1][j]
        }
        if j-1 >= 0 { 
            count += grid[i][j-1]
        }
        if j+1 < len(grid[0]) {
            count += grid[i][j+1]
        }
        return count
    }
    

Log in to reply
 

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