题目链接:https://leetcode-cn.com/problems/surrounded-regions/
边界的O和与之相连的不会被改,所以干脆先把边界及其相连的所有O区域全部搜出来变成个别的保护一下,然后全图剩下的O就都得变成X了,最后再把保护的变回O就可以了
代码如下:
class Solution {
public:
void dfs(int x, int y, vector<vector<char>>& board) {
if(board[x][y] == 'O') {
board[x][y] = 'N'; //保护:把边界'O'暂时变成'N'
} else if(board[x][y] != 'O') {
return;
}
int dx[4] = {-1, 0, 1, 0};
int dy[4] = {0, 1, 0, -1};
for(int i = 0; i < 4; i++) {
int xx = x + dx[i], yy = y + dy[i];
if(xx >= 0 && xx < board.size() && yy >= 0 && yy < board[0].size()) {
dfs(xx, yy, board);
}
}
}
void solve(vector<vector<char>>& board) {
if(board.size() == 0 || board[0].size() == 0) {
return;
}
//处理四边的'O'及其相连接的所有'O'
for(int i = 0; i < board.size(); i++) {
if(board[i][0] == 'O') {
dfs(i, 0, board);
}
if(board[i][board[0].size() - 1] == 'O') {
dfs(i, board[0].size() - 1, board);
}
}
for(int j = 0; j < board[0].size(); j++) {
if(board[0][j] == 'O') {
dfs(0, j, board);
}
if(board[board.size() - 1][j] == 'O') {
dfs(board.size() - 1, j, board);
}
}
//此时全图剩下的'O'都需要变成'X',同时保护的'N'可以变回来
for(int i = 0; i < board.size(); i++) {
for(int j = 0; j < board[0].size(); j++) {
if(board[i][j] == 'O') {
board[i][j] = 'X';
} else if(board[i][j] == 'N') {
board[i][j] = 'O';
}
}
}
}
};