1. 题⽬链接:130.被围绕的区域
2. 题⽬描述:
3. 解法:
算法思路:
正难则反。 可以先利⽤dfs 将与边缘相连的'0' 区域做上标记,然后重新遍历矩阵,将没有标记过的'0' 修改成'X' 即可。
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);
}
}
}
}