Skip to content

Commit

Permalink
Create 1905-count-sub-islands.go
Browse files Browse the repository at this point in the history
  • Loading branch information
AP-Repositories authored Jan 4, 2023
1 parent ce6fbca commit a21eac9
Showing 1 changed file with 39 additions and 0 deletions.
39 changes: 39 additions & 0 deletions go/1905-count-sub-islands.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
func countSubIslands(grid1 [][]int, grid2 [][]int) int {
ROWS, COLS := len(grid1), len(grid1[0])
visit := make(map[int]bool)

var dfs func(int, int) bool
dfs = func(r, c int) bool {
if (
r < 0 ||
c < 0 ||
r == ROWS ||
c == COLS ||
grid2[r][c] == 0 ||
visit[r*COLS + c]) {
return true
}

visit[r*COLS + c] = true
res := true
if grid1[r][c] == 0 {
res = false
}

res = dfs(r - 1, c) && res
res = dfs(r + 1, c) && res
res = dfs(r, c - 1) && res
res = dfs(r, c + 1) && res
return res
}

count := 0
for r := 0; r < ROWS; r++ {
for c := 0; c < COLS; c++ {
if grid2[r][c] != 0 && !visit[r*COLS + c] && dfs(r, c) {
count += 1
}
}
}
return count
}

0 comments on commit a21eac9

Please sign in to comment.