-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy path00695-max_area_of_island.go
58 lines (46 loc) · 1.08 KB
/
00695-max_area_of_island.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
// 695: Max Area Of Island
// https://leetcode.com/problems/max-area-of-island
package main
import "fmt"
func dfs(grid [][]int, i, j int) int {
if i < 0 || i >= len(grid) || j < 0 || j >= len(grid[0]) {
return 0
}
if grid[i][j] == 0 {
return 0
}
grid[i][j] = 0
return 1 + dfs(grid, i+1, j) + dfs(grid, i-1, j) + dfs(grid, i, j+1) + dfs(grid, i, j-1)
}
// SOLUTION
func maxAreaOfIsland(grid [][]int) int {
m, n := len(grid), len(grid[0])
result := 0
for i := 0; i < m; i++ {
for j := 0; j < n; j++ {
if grid[i][j] == 1 {
curr := dfs(grid, i, j)
if curr > result {
result = curr
}
}
}
}
return result
}
func main() {
// INPUT
grid := [][]int{
{0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0},
{0, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0},
{0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 0, 0},
{0, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0},
{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0},
{0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0},
{0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0},
}
// OUTPUT
result := maxAreaOfIsland(grid)
fmt.Println(result)
}