Skip to content

Commit a21eac9

Browse files
Create 1905-count-sub-islands.go
Accepted submission: _https://leetcode.com/submissions/detail/870821099/_
1 parent ce6fbca commit a21eac9

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed

go/1905-count-sub-islands.go

+39
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
func countSubIslands(grid1 [][]int, grid2 [][]int) int {
2+
ROWS, COLS := len(grid1), len(grid1[0])
3+
visit := make(map[int]bool)
4+
5+
var dfs func(int, int) bool
6+
dfs = func(r, c int) bool {
7+
if (
8+
r < 0 ||
9+
c < 0 ||
10+
r == ROWS ||
11+
c == COLS ||
12+
grid2[r][c] == 0 ||
13+
visit[r*COLS + c]) {
14+
return true
15+
}
16+
17+
visit[r*COLS + c] = true
18+
res := true
19+
if grid1[r][c] == 0 {
20+
res = false
21+
}
22+
23+
res = dfs(r - 1, c) && res
24+
res = dfs(r + 1, c) && res
25+
res = dfs(r, c - 1) && res
26+
res = dfs(r, c + 1) && res
27+
return res
28+
}
29+
30+
count := 0
31+
for r := 0; r < ROWS; r++ {
32+
for c := 0; c < COLS; c++ {
33+
if grid2[r][c] != 0 && !visit[r*COLS + c] && dfs(r, c) {
34+
count += 1
35+
}
36+
}
37+
}
38+
return count
39+
}

0 commit comments

Comments
 (0)