给你一个 m x n 的矩阵 board ,由若干字符 ‘X’ 和 ‘O’ ,找到所有被 ‘X’ 围绕的区域,并将这些区域里所有的 ‘O’ 用 ‘X’ 填充。
class Solution {
public void solve(char[][] board) {
//先把边界走一把,然后把O的下标位置加入集合队列
//同时使用一个记录数组记录,1为O
//然后bfs去搜索和边界O连通的O,去标记
//在通过标记数组去把原数组没被标记的O改为X
ArrayDeque<int[]> q = new ArrayDeque<>();
int m = board[0].length;//列
int n = board.length;//行
int index[][] = new int[n][board[0].length];
for(int i = 0 ;i< n ; i++){
if(board[i][0] == 'O'){
int p[]= new int[]{i,0};
index[i][0] = 1;
q.push(p);
}
if(board[i][m-1] == 'O'){
int p[]= new int[]{i,m-1};
index[i][m-1] = 1;
q.push(p);
}
}
for(int i = 0 ;i< m ; i++){
if(board[0][i] == 'O'){
int p[]= new int[]{0,i};
index[0][i] = 1;
q.push(p);
}
if(board[n-1][i] == 'O'){
int p[]= new int[]{n-1 ,i};
index[n-1][i] = 1;
q.push(p);
}
}
//bfs去搜索
while(!q.isEmpty()){
int pos[] = q.poll();
int x = pos[0] , y = pos[1];
if(x-1 >= 0 && board[x-1][y] == 'O' && index[x-1][y] == 0){
index[x-1][y] = 1;
int p[]= new int[]{x-1,y};
q.push(p);
}
if(x+1 < n && board[x+1][y] == 'O' && index[x+1][y] == 0){
index[x+1][y] = 1;
int p[]= new int[]{x+1,y};
q.push(p);
}
if(y-1 >= 0 && board[x][y-1] == 'O' && index[x][y-1] == 0){
index[x][y-1] = 1;
int p[]= new int[]{x,y-1};
q.push(p);
}
if(y+1 < m && board[x][y+1] == 'O' && index[x][y+1] == 0){
index[x][y+1] = 1;
int p[]= new int[]{x,y+1};
q.push(p);
}
}
//在通过标记数组去把原数组没被标记的O改为X
for(int i = 1 ; i < n ;i++){
for(int j = 1 ; j < m ; j++){
if(index[i][j] == 0 && board[i][j] == 'O'){
board[i][j] = 'X';
}
}
}
}
}