You are given an m x n
matrix board
containing letters 'X'
and 'O'
, capture regions that are surrounded:
- Connect: A cell is connected to adjacent cells horizontally or vertically.
- Region: To form a region connect every
'O'
cell. - Surround: The region is surrounded with
'X'
cells if you can connect the region with'X'
cells and none of the region cells are on the edge of theboard
.
A surrounded region is captured by replacing all 'O'
s with 'X'
s in the input matrix board
.
Example 1:
Input: board = [["X","X","X","X"],["X","O","O","X"],["X","X","O","X"],["X","O","X","X"]]
Output: [["X","X","X","X"],["X","X","X","X"],["X","X","X","X"],["X","O","X","X"]]
Explanation:
In the above diagram, the bottom region is not captured because it is on the edge of the board and cannot be surrounded.
Example 2:
Input: board = [["X"]]
Output: [["X"]]
Constraints:
m == board.length
n == board[i].length
1 <= m, n <= 200
board[i][j]
is'X'
or'O'
.
class Solution {
int m, n;
void dfs(vector<vector<char> >& board,int x,int y){
if(x < 0 || x >= n || y < 0|| y >= m || board[x][y] != 'O'){
return;
}
board[x][y] = 'A';
dfs(board,x ,y + 1);
dfs(board,x ,y - 1);
dfs(board, x + 1, y);
dfs(board, x - 1, y);
}
public:
void solve(vector<vector<char>>& board) {
n = board.size();
m = board[0].size();
if(n == 0 )
return;
for(int i = 0;i < m;i ++){
dfs(board, 0, i);
dfs(board, n-1,i);
}
for(int i = 0;i < n;i ++){
dfs(board, i, 0);
dfs(board, i, m-1);
}
for(int i = 0;i < n;i ++){
for(int j = 0;j < m;j ++){
if (board[i][j] == 'A') {
board[i][j] = 'O';
} else if (board[i][j] == 'O') {
board[i][j] = 'X';
}
}
}
}
};