题目描述:
给你一个 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'
思路描述:
这道题,我们换一种思路进行思考的话,就会很简单,我们只需要遍历二维矩阵的最边缘的部分,对于最边缘的部分查找是否有'O',如果有,就在此点按照'O'的路径进行深度优先遍历,并将遍历到的点,修改值为其他字符如'A',然后再遍历二维数组,元素为'O'的都修改为'X',元素为'A'的都修改为'O',最后我们这个二维矩阵即为所得。
代码:
class Solution {
public void solve(char[][] board) {
int rows=board.length;
int cols=board[0].length;
for(int i=0;i<rows;i++){
if(i==0 || i==rows-1){
for(int j=0;j<cols;j++){
dfs(board,i,j);
}
}else{
dfs(board,i,0);
dfs(board,i,cols-1);
}
}
for(int i=0;i<rows;i++){
for(int j=0;j<cols;j++){
if(board[i][j]=='O'){
board[i][j]='X';
}
if(board[i][j]=='A'){
board[i][j]='O';
}
}
}
}
public void dfs(char[][] board,int row,int col){
if(board[row][col]=='O'){
board[row][col]='A';
if(row+1<board.length){
dfs(board,row+1,col);
}
if(row-1>0){
dfs(board,row-1,col);
}
if(col+1<board[0].length){
dfs(board,row,col+1);
}
if(col-1>0){
dfs(board,row,col-1);
}
}
}
}