Skip to content

Commit

Permalink
Create 0463-island-perimeter.go
Browse files Browse the repository at this point in the history
  • Loading branch information
AP-Repositories authored Jan 4, 2023
1 parent 512a00e commit e8b926e
Showing 1 changed file with 29 additions and 0 deletions.
29 changes: 29 additions & 0 deletions go/0463-island-perimeter.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
func islandPerimeter(grid [][]int) int {
ROWS, COLS := len(grid), len(grid[0])
visit := make(map[int]bool)

var dfs func(int, int) int
dfs = func(i, j int) int {
if i >= ROWS || j >= COLS || i < 0 || j < 0 || grid[i][j] == 0 {
return 1
} else if visit[i*COLS + j] {
return 0
}

visit[i*COLS + j] = true
perim := dfs(i, j + 1)
perim += dfs(i + 1, j)
perim += dfs(i, j - 1)
perim += dfs(i - 1, j)
return perim
}

for i := 0; i < ROWS; i++ {
for j := 0; j < COLS; j++ {
if grid[i][j] != 0 {
return dfs(i, j)
}
}
}
return -1
}

0 comments on commit e8b926e

Please sign in to comment.