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
|
func solve(board [][]byte) {
h, w := len(board), len(board[0])
visited := make([][]bool, h)
for i := 0; i < h; i++ {
visited[i] = make([]bool, w)
}
dirs := [][2]int{{1, 0}, {0, 1}, {-1, 0}, {0, -1}}
var bfs func(i, j int)
bfs = func(i, j int) {
visited[i][j] = true
var queue [][2]int
queue = append(queue, [2]int{i, j})
for len(queue) > 0 {
coordinate := queue[0]
x, y := coordinate[0], coordinate[1]
queue = queue[1:]
for _, dir := range dirs {
nx, ny := x+dir[0], y+dir[1]
if 0 <= nx && nx < h && 0 <= ny && ny < w && board[nx][ny] == 'O' && !visited[nx][ny] {
visited[nx][ny] = true
queue = append(queue, [2]int{nx, ny})
}
}
}
}
for j := 0; j < w; j++ {
if board[0][j] == 'O' && !visited[0][j] {
bfs(0, j)
}
if board[h-1][j] == 'O' && !visited[h-1][j] {
bfs(h-1, j)
}
}
for i := 1; i < h-1; i++ {
if board[i][0] == 'O' && !visited[i][0] {
bfs(i, 0)
}
if board[i][w-1] == 'O' && !visited[i][w-1] {
bfs(i, w-1)
}
}
for i := 0; i < h; i++ {
for j := 0; j < w; j++ {
if board[i][j] == 'O' && !visited[i][j] {
board[i][j] = 'X'
}
}
}
}
|