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
// @Title: 被围绕的区域 (Surrounded Regions)
// @Author: 15816537946@163.com
// @Date: 2020-06-25 07:15:36
// @Runtime: 32 ms
// @Memory: 5.9 MB
func solve(board [][]byte)  {
	if board == nil   {
		return 
	}

	var dfs func( int, int)
	dfs = func(i,j int ) {
		// if i < 0 || j< 0 || i> len(board)-1 || j > len(board[0])-1 || board[i][j] == 'X' || board[i][j] == '#' {
		if i < 0 || j< 0 || i>= len(board) || j >= len(board[0]) || board[i][j] == 'X' || board[i][j] == '#' {
			return 
		}
		board[i][j] = '#'
		dfs(i+1,j)
		dfs(i-1,j)
		dfs(i,j-1)
		dfs(i,j+1)
	}

	for i := range board {
		for j := range  board[0] {
			if (i == 0 || j == 0 || i== len(board)-1 || j == len(board[0])-1) && board[i][j] == 'O' {
				dfs(i,j)
			}
		}
	}

	// 替换&&填充元素
	for i := range board {
		for j := range board[0] {
			if board[i][j] == '#' {
				board[i][j] = 'O'
				continue
			}
			if board[i][j] == 'O' {
				board[i][j] = 'X'
			}
		}
	}
}