题目描述
Given a 2D board containing'X'and'O', capture all regions surrounded by'X'.
A region is captured by flipping all'O's into'X's in that surrounded region .
For example,
X X X X X O O X X X O X X O X X
After running your function, the board should be:
X X X X X X X X X X X X X O X X思路:1,从四周的O开始深度搜索,将能搜到的O全置为×;
2,遍历所有元素,若当前元素为×将其置为O,若为O将其置为X。
代码实现:
1
class Solution {
2
public:
3
void solve(vector<vector<char>> &board) {
4
//从四周的O开始深度搜索,将能搜到的O全置为×
5
//扫描所有元素,将×置为O,将O置为X。
6
if (board.size() <= 2 || board[0].size() <=2)
7
return ;
8
for (int i=0; i<board[0].size(); ++i){
9
dfs(board, 0, i);
10
dfs(board, board.size()-1, i);
11
}
12
for (int i=1; i<board.size()-1; i++){
13
dfs(board, i, 0);
14
dfs(board, i, board[0].size()-1);
15
}
16
17
for (int i=0; i<board.size(); ++i)
18
for (int j=0; j<board[0].size(); ++j){
19
if (board[i][j] == '*')
20
board[i][j] = 'O';
21
else if (board[i][j] == 'O')
22
board[i][j] = 'X';
23
}
24
return ;
25
}
26
27
//深度搜索
28
void dfs(vector<vector<char>> &board, int row, int col){
29
if (board[row][col] == 'O'){
30
board[row][col] = '*';
31
//
32
if (row > 1)
33
dfs(board, row-1, col);
34
if (col > 1)
35
dfs(board, row, col-1);
36
if (row < board.size()-1){
37
dfs(board, row+1, col);
38
}
39
if (col < board[0].size()-1){
40
dfs(board, row, col+1);
41
}
42
}
43
return ;
44
}
45
};
您的代码已保存