-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathleetcode130.cpp
52 lines (48 loc) · 1.37 KB
/
leetcode130.cpp
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
50
51
52
/*
First, check the four border of the matrix. If there is a element is
'O', alter it and all its nei***or 'O' elements to '1'.
Then ,alter all the 'O' to 'X'
At last,alter all the '1' to 'O'
For example:
X X X X X X X X X X X X
X X O X -> X X O X -> X X X X
X O X X X 1 X X X O X X
X O X X X 1 X X X O X X
*/
class Solution {
public:
void solve(vector<vector<char>>& board) {
if(board.size()==0){
return;
}
int rows=board.size(),cols=board[0].size();
for(int i=0;i<rows;i++){
dfs(board,i,0);
dfs(board,i,cols-1);
}
for(int j=1;j<cols-1;j++){
dfs(board,0,j);
dfs(board,rows-1,j);
}
for(int i=0;i<rows;i++){
for(int j=0;j<cols;j++){
if(board[i][j]=='1'){
board[i][j]='O';
}
else{
board[i][j]='X';
}
}
}
}
private:
void dfs(vector<vector<char>>& board,int i,int j){
if(i>=0&&i<board.size()&&j>=0&&j<board[0].size()&&board[i][j]=='O'){
board[i][j]='1';
dfs(board,i-1,j);
dfs(board,i+1,j);
dfs(board,i,j-1);
dfs(board,i,j+1);
}
}
};