1、
2、这是一道dfs问题
把所有边上的O变为A并DFS其上下左右的相连的O变为A,后面这些A要变成O
其余O变为X
for(int i = 0; i < n; i++)
{
dfs(board,i,0);
dfs(board,i,m-1);
}
for(int i = 0; i < m; i++)
{
dfs(board,0,i);
dfs(board,n-1,i);
}
这就是遍历4条边用的
class Solution {
int n,m;
public:
void solve(vector<vector<char>>& board) {
n = board.size();
if(n == 0) return;
m = board[0].size();
for(int i = 0; i < n; i++)
{
dfs(board,i,0);
dfs(board,i,m-1);
}
for(int i = 0; i < m; i++)
{
dfs(board,0,i);
dfs(board,n-1,i);
}
for(int i = 0; i < n; i++)
{
for(int j = 0; j < m; j++)
{
if(board[i][j] == 'A')board[i][j] = 'O';
else board[i][j] = 'X';
}
}
}
void dfs(vector<vector<char>>& board,int x, int y)
{
if(x < 0 || x >= n || y < 0 || y >= m || board[x][y] != 'O')return;
else{
board[x][y] = 'A';
dfs(board,x-1,y);
dfs(board,x+1,y);
dfs(board,x,y+1);
dfs(board,x,y-1);
}
}
};