1、题目
https://leetcode-cn.com/problems/surrounded-regions/
2、题解
这是我学习到的一个思路,大概逻辑是
只要把不和边界O连通的 O 换位X就可以了。
所以我们只需要遍历一下四条边,将于边界O相连的O做上标记,最后遍历char[][]数组,来改变一下字母和符号就可以了。在找到边界O时,需要向它的四周去找和它相通的O,这里就用到了队列,被连通的O的坐标首先入队,然后出队,判断它的四周是否有连通的O,入队,再出队,判断是否有连通的O……直到队列中没有元素。
3、代码
class Solution {
public void solve(char[][] board) {
//排除异常
if(board.length==0||board[0].length==0){
return;
}
int row = board.length;
int col = board[0].length;
for (int i = 0; i < row; i++) {
if (board[i][0] == 'O') helper(board,i,0);
if (board[i][col-1] == 'O') helper(board,i,col-1);
}
for (int i = 0; i < col; i++) {
if (board[0][i] == 'O') helper(board,0,i);
if (board[row-1][i] == 'O') helper(board,row-1,i);
}
for (int i = 0; i < row; i++)
for (int j = 0; j < col; j++) {
if (board[i][j] == 'O') board[i][j] = 'X';
else if (board[i][j] == '*') board[i][j] = 'O';
}
}
public void helper( char[][] board , int x, int y ){
int[][] nums = {{0,1},{0,-1},{1,0},{-1,0}};
Queue<Integer[]> queue = new LinkedList<>();
Integer[] integers = {x,y};
queue.offer(integers);
board[x][y] = '*';
while ( queue != null && queue.size() != 0){
Integer[] temp = queue.poll();
for (int i = 0; i < 4; i++) {
Integer newX = temp[0]+nums[i][0];
Integer newY = temp[1]+nums[i][1];
if (newX < 0 || newX >= board.length || newY < 0 || newY >= board[0].length) continue;
if (board[newX][newY] == 'O'){
board[newX][newY] = '*';
Integer[] t = {newX, newY};
queue.offer(t);
}
}
}
}
}
网友评论