Medium | LeetCode 130. 被围绕的区域 | 矩阵 + DFS
130. 被围绕的区域
给你一个 m x n
的矩阵 board
,由若干字符 'X'
和 'O'
,找到所有被 'X'
围绕的区域,并将这些区域里所有的 'O'
用 'X'
填充。
示例 1:
输入:board = [["X","X","X","X"],["X","O","O","X"],["X","X","O","X"],["X","O","X","X"]]
输出:[["X","X","X","X"],["X","X","X","X"],["X","X","X","X"],["X","O","X","X"]]
解释:被围绕的区间不会存在于边界上,换句话说,任何边界上的 'O' 都不会被填充为 'X'。 任何不在边界上,或不与边界上的 'O' 相连的 'O' 最终都会被填充为 'X'。如果两个元素在水平或垂直方向相邻,则称它们是“相连”的。
示例 2:
输入:board = [["X"]]
输出:[["X"]]
提示:
m == board.length
n == board[i].length
1 <= m, n <= 200
board[i][j]
为'X'
或'O'
解体方法
常规的DFS搜索题目。需要区分边界节点和内部节点。先从边界使用DFS算法将搜索到的'O'字符变成'A'。这样剩下的'O'节点就都是内部节点了。然后'A'节点就都是原来的'O'节点。最后扫描一遍二维数组, 将'A'节点还原成'O'节点, 将剩下的'O'节点变成'X'节点。
public void solve(char[][] board) {
if (board.length == 0) {
return;
}
int row = board.length, colume = board[0].length;
// 从四个边界进行DFS搜索
for (int i = 0; i < row; i++) {
// 左边界
dfs(board, i , 0);
// 右边界
dfs(board, i, colume - 1);
}
for (int i = 0; i < colume; i++) {
// 上边界
dfs(board, 0, i);
// 下边界
dfs(board, row - 1, i);
}
for (int i = 0; i < row; i++) {
for (int j = 0; j < colume; j++) {
if (board[i][j] == 'A') {
board[i][j] = 'O';
} else if (board[i][j] == 'O') {
board[i][j] = 'X';
}
}
}
}
private void dfs(char[][] board, int x, int y) {
if (x < 0 || x >= board.length || y < 0 || y >= board[0].length || board[x][y] != 'O') {
return;
}
board[x][y] = 'A';
dfs(board, x - 1, y);
dfs(board, x, y + 1);
dfs(board, x + 1, y);
dfs(board, x, y - 1);
}