# （算法）被围绕的区域————＜递归＞

41 篇文章 0 订阅

## 3. 解法：

### C++算法代码：

class Solution
{
public:
int dx[4] = { 1,0,-1,0 };
int dy[4] = { 0,1,0,-1 };
int temp[200][200] = { 0 };    //状态数组
int m,n;    //行列数
void dfs(vector<vector<char>>& board, int x, int y)
{
for (int i = 0; i < 4; i++)
{
int X = x + dx[i], Y = y + dy[i];
//合法性判断
if (X < 0 || X >= m || Y < 0 || Y >= n || temp[X][Y] || board[X][Y] == 'X')
{
continue;
}
//修改值
temp[X][Y] = 1;
dfs(board, X, Y);
}
}
void solve(vector<vector<char>>& board)
{
m=board.size(),n=board[0].size();
//遍历列
for(int i=0;i<m;i++)
{
//第一列
if(board[i][0]=='O')
{
temp[i][0]=1;
dfs(board,i,0);
}
//最后一列
if(board[i][n-1]=='O')
{
temp[i][n-1]=1;
dfs(board,i,n-1);
}
}
//遍历列
for(int i=0;i<n;i++)
{
//第一行
if(board[0][i]=='O')
{
temp[0][i]=1;
dfs(board,0,i);
}
//最后一行
if(board[m-1][i]=='O')
{
temp[m-1][i]=1;
dfs(board,m-1,i);
}
}
//修改
for(int i=1;i<m-1;i++)
{
for(int j=1;j<n-1;j++)
{
if(board[i][j]=='O'&&temp[i][j]==0)
{
board[i][j]='X';
}
}
}
}
};

### Java算法代码：

class Solution
{
int m, n;
int[] dx = { 1, -1, 0, 0 };
int[] dy = { 0, 0, 1, -1 };
public void solve(char[][] board)
{
m = board.length; n = board[0].length;
// 1. 先把边界的 O 相连的联通块，全部修改成 '.'
for (int j = 0; j < n; 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++)
{
if (board[i][0] == 'O') dfs(board, i, 0);
if (board[i][n - 1] == 'O') dfs(board, i, n - 1);
}
// 2. 还原
for (int i = 0; i < m; i++)
for (int j = 0; j < n; j++)
{
if (board[i][j] == '.') board[i][j] = 'O';
else if (board[i][j] == 'O') board[i][j] = 'X';
}
}
public void dfs(char[][] board, int i, int j)
{
board[i][j] = '.';
for (int k = 0; k < 4; k++)
{
int x = i + dx[k], y = j + dy[k];
if (x >= 0 && x < m && y >= 0 && y < n && board[x][y] == 'O')
{
dfs(board, x, y);
}
}
}
}

• 4
点赞
• 2
收藏
觉得还不错? 一键收藏
• 打赏
• 0
评论
07-20 1072
11-03 1270
03-15 523
05-23 322
06-24 608
03-30 1057
02-03 397
09-11 1062
09-11 235
09-09 977
09-14 631
09-10 418

¥1 ¥2 ¥4 ¥6 ¥10 ¥20

1.余额是钱包充值的虚拟货币，按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载，可以购买VIP、付费专栏及课程。