一开始还用一张图来存当前结点的O是否可以改,简直浪费内存。遍历四条边界,从边界的O进行dfs,将dfs能到达的O均改为一个特殊符号。最后遍历这张图,是特殊符号的改回O,不是特殊符号的O改成X
class Solution {
public:
void dfs(vector<vector<char>>& board,int row, int col){
if(row < 0 || row >= board.size() || col < 0 || col >= board[0].size()) return;
if(board[row][col] != 'O') return;
board[row][col] = 'P';
dfs(board,row+1,col);
dfs(board,row,col+1);
dfs(board,row-1,col);
dfs(board,row,col-1);
}
void solve(vector<vector<char>>& board) {
//边界上的O不会被填充为X,或者和边界上的O相邻的O都不会被填充成X
//来一张可填充的二维数组,从边界上的O开始dfs,只要它能到达的O全部设为不可填充
//然后再次遍历,填充那些可填充的O
//不用新图记录,将相连的O改成P,然后在遍历时把P改回O即可,把O改成X
if(board.size() == 0 || board[0].size() == 0) return;
for(int i = 0; i < board[0].size(); ++i){
dfs(board,0,i);
dfs(board,board.size()-1,i);
}
for(int i = 0; i < board.size(); ++i){
dfs(board,i,0);
dfs(board,i,board[0].size()-1);
}
for(int i = 0; i < board.size(); ++i){
for(int j = 0; j < board[0].size(); ++j){
if(board[i][j] == 'P') board[i][j] = 'O';
else if(board[i][j] == 'O') board[i][j] = 'X';
}
}
}
};
从4个边界出发,找O,从这个位置进行dfs,将和边界上的O相邻的O全部改为特殊字符
再次遍历board,将O改为X,将特殊字符改为O
class Solution {
public:
void dfs(vector<vector<char>>& board, int row, int col){
if(row<0 || row >= board.size() || col < 0 || col >= board[0].size()) return;
if(board[row][col] != 'O') return;
board[row][col] = 'P';
dfs(board,row+1,col);
dfs(board,row,col+1);
dfs(board,row-1,col);
dfs(board,row,col-1);
}
void solve(vector<vector<char>>& board) {
//找到被X围绕的区域,将O用X填充,边界上的O不会被填充
//从4个边界出发,找O,从这个位置进行dfs,将和边界上的O相邻的O全部改为特殊字符
//再次遍历board,将O改为X,将特殊字符改为O
int row = board.size();
int col = board[0].size();
//不用进行判断,直接到dfs里面进行判断就行了
for(int i = 0; i < row; ++i) dfs(board,i,0);
for(int i = 0; i < row; ++i) dfs(board,i,col-1);
for(int j = 0; j < col; ++j) dfs(board,0,j);
for(int j = 0; j < col; ++j) dfs(board,row-1,j);
for(int i = 0; i < row; ++i){
for(int j = 0; j < col; ++j){
if(board[i][j] == 'O') board[i][j] = 'X';
else if(board[i][j] == 'P') board[i][j] = 'O';
}
}
}
};