LeetCode——被围绕的区域
Q:现在有一个仅包含‘X’和‘O’的二维板,请捕获所有的被‘X’包围的区域
捕获一个被包围区域的方法是将被包围区域中的所有‘O’变成‘X’
例如
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
A:
1.与边界上面的O相连的那些O不是被包围的,所以利用深度搜索将这些与边界相连(包括边界)的O变成*
2.剩下的O就是被包围的,将他们改成X
3.再将*变回O
public int rowNum = 0;
public int colNum = 0;
public void solve(char[][] board) {
if(board == null || board.length <= 0|| board[0].length <= 0){
return;
}
rowNum = board.length;
colNum = board[0].length;
for(int i = 0; i < colNum; i++){
dfs(board, 0, i);
dfs(board, rowNum-1, i);
}
for(int i = 0; i < rowNum; i++){
dfs(board, i, 0);
dfs(board, i, colNum-1);
}
for(int i = 0; i < rowNum; i++){
for(int j = 0; j < colNum; j++){
if(board[i][j] == 'O'){
board[i][j] = 'X';
}
}
}
for(int i = 0; i < rowNum; i++){
for(int j = 0; j < colNum; j++){
if(board[i][j] == '*'){
board[i][j] = 'O';
}
}
}
}
private void dfs(char[][] board, int row, int col) {
if(board[row][col] == 'O'){
board[row][col] = '*';
if(row > 1){
dfs(board, row-1, col);
}
if(col > 1){
dfs(board, row, col-1);
}
if(row < rowNum-1){
dfs(board, row+1, col);
}
if(col < colNum-1){
dfs(board, row, col+1);
}
}
}