一、题目
Given an m x n matrix board containing ‘X’ and ‘O’, capture all regions that are 4-directionally surrounded by ‘X’.
A region is captured by flipping all 'O’s into 'X’s in that surrounded region.
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: Notice that an ‘O’ should not be flipped if:
- It is on the border, or
- It is adjacent to an ‘O’ that should not be flipped.
The bottom ‘O’ is on the border, so it is not flipped.
The other three ‘O’ form a surrounded region, so they are flipped.
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’.
二、题解
visited数组法——使用额外空间
与上题的方法类似,遍历四条边上值为’O’的值,并找出与其相邻的所有’O’,将其标记为已走过,最后遍历整张图,找到没走过的值为’O’的各自,并将其修改为’X’即可。本方法由于使用了visited数组,因此空间复杂度较高。
class Solution {
public:
int dirs[4][2] = {1,0,0,1,-1,0,0,-1};
void dfs(vector<vector<char>>& board,vector<vector<bool>>& visted,int x,int y){
visted[x][y] = true;
for(int i = 0;i < 4;i++){
int nextX = x + dirs[i][0];
int nextY = y + dirs[i][1];
if(nextX < 0 || nextX >= board.size() || nextY < 0 || nextY >= board[0].size()) continue;
if(board[nextX][nextY] == 'O' && visted[nextX][nextY] == false){
visted[nextX][nextY] = true;
dfs(board,visted,nextX,nextY);
}
}
}
void solve(vector<vector<char>>& board) {
int m = board.size();
int n = board[0].size();
vector<vector<bool>> visted(m,vector<bool>(n,false));
//对左和右进行遍历
for(int i = 0;i < m;i++){
if(board[i][0] == 'O' && visted[i][0] == false) dfs(board,visted,i,0);
if(board[i][n-1] == 'O' && visted[i][n-1] == false) dfs(board,visted,i,n-1);
}
//对上和下进行遍历
for(int j = 1;j < n - 1;j++){
if(board[0][j] == 'O' && visted[0][j] == false) dfs(board,visted,0,j);
if(board[m-1][j] == 'O' && visted[m-1][j] == false) dfs(board,visted,m-1,j);
}
//改变被包围飞地的值
for(int i = 0;i < m;i++){
for(int j = 0;j < n;j++){
if(board[i][j] == 'O' && visted[i][j] == false) board[i][j] = 'X';
}
}
}
};
不使用额外空间的方法——直接在原数组中使用数字A进行标记
class Solution {
public:
int dirs[4][2] = {1,0,0,1,-1,0,0,-1};
void dfs(vector<vector<char>>& board,int x,int y){
board[x][y] = 'A';
for(int i = 0;i < 4;i++){
int nextX = x + dirs[i][0];
int nextY = y + dirs[i][1];
if(nextX < 0 || nextX >= board.size() || nextY < 0 || nextY >= board[0].size()) continue;
if(board[nextX][nextY] == 'O'){
board[nextX][nextY] = 'A';
dfs(board,nextX,nextY);
}
}
}
void solve(vector<vector<char>>& board) {
int m = board.size();
int n = board[0].size();
//对左和右进行遍历
for(int i = 0;i < m;i++){
if(board[i][0] == 'O') dfs(board,i,0);
if(board[i][n-1] == 'O') dfs(board,i,n-1);
}
//对上和下进行遍历
for(int j = 1;j < n - 1;j++){
if(board[0][j] == 'O') dfs(board,0,j);
if(board[m-1][j] == 'O') dfs(board,m-1,j);
}
//改变被包围飞地的值
for(int i = 0;i < m;i++){
for(int j = 0;j < n;j++){
if(board[i][j] == 'O') board[i][j] = 'X';
else if(board[i][j] == 'A') board[i][j] = 'O';
}
}
}
};