Recursive solution with golang


  • 0
    S
    func islandPerimeter(grid [][]int) int {
        rows := len(grid)
        if rows == 0 {
            return 0
        }
        cols := len(grid[0])
        if cols == 0 {
            return 0
        }
        for i:=0; i<rows; i++ {
            for j:=0; j<cols; j++ {
                if grid[i][j] == 1 {
                    return getPerimeter(grid, rows, cols, i, j)
                }
            }
        }
        return 0
    }
    
    func getPerimeter(grid [][]int, rows int, cols int, i int, j int) int {
        var perimeter int = 0
        grid[i][j] = 2
        if i==0 || grid[i-1][j] == 0 {
            perimeter += 1
        } else if grid[i-1][j] == 1 {
            perimeter += getPerimeter(grid, rows, cols, i-1, j)
        }
        if j==0 || grid[i][j-1] == 0 {
            perimeter += 1
        } else if grid[i][j-1] == 1{
            perimeter += getPerimeter(grid, rows, cols, i, j-1)
        }
        if i==rows-1 || grid[i+1][j] == 0 {
            perimeter +=1
        } else if grid[i+1][j] == 1{
            perimeter += getPerimeter(grid, rows, cols, i+1, j)
        }
        if j==cols-1 || grid[i][j+1] == 0 {
            perimeter += 1
        } else if grid[i][j+1] == 1 {
            perimeter += getPerimeter(grid, rows, cols, i, j+1)
        }
        return perimeter
    }
    

Log in to reply
 

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