hackathon/question/q04/part2.go

38 lines
699 B
Go

package q04
func check(x, y, n, m int) bool {
return x >= 0 && y >= 0 && x < n && y < m
}
var dirs = [][]int{{-1, 0}, {0, -1}, {1, 0}, {0, 1}}
func dfs(grid [][]rune, vis [][]bool, x, y, n, m int) {
if !check(x, y, n, m) || grid[x][y] == ' ' || vis[x][y] {
return
}
vis[x][y] = true
for _, d := range dirs {
x1, y1 := x+d[0], y+d[1]
dfs(grid, vis, x1, y1, n, m)
}
}
func solveP2(grid [][]rune) int {
var res int
n := len(grid)
m := len(grid[0])
vis := make([][]bool, n)
for i := range vis {
vis[i] = make([]bool, m)
}
for i := range grid {
for j := range grid[i] {
if !vis[i][j] && grid[i][j] == 'X' {
res++
dfs(grid, vis, i, j, n, m)
}
}
}
return res
}