原题链接:
https://leetcode.cn/problems/surrounded-regions/description/
完成情况:
解题思路:
这段代码是一个解决广度优先遍历问题的算法,目的是找出一个二维字符数组中所有未被’X’包围的’O’,并将这些’O’标记为’X’。以下是代码的清晰简洁的解释:
- 首先定义了一个Solution类,其中包含了一个position数组,表示四个方向的移动(上、右、下、左)。
- solve方法接收一个二维字符数组board作为输入,首先获取行数rowSize和列数colSize,并初始化一个visited数组用于标记已访问的位置。
- 创建一个队列queue(使用ArrayDeque实现),从矩阵的四个边开始遍历,将边上的’O’位置标记为已访问,并加入队列。
- 然后遍历上下两边(不包括四个角),同样标记’O’位置并加入队列。
- 进行广度优先遍历,从队列中取出一个位置,检查该位置的上下左右四个相邻位置,将未访问过的且为’O’的位置标记为已访问并加入队列。
- 最后遍历整个数组,将未被标记的’O’修改为’X’。
这段代码实现了通过广度优先遍历找出未被’X’包围的’O’,并将其标记为’X’的功能。
参考代码:
package 代码随想录.图论;
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.Queue;
public class _130被围绕的区域 {
int position[][] = {
{1,0},
{-1,0},
{0,1},
{0,-1}
};
/**
*
* @param board
*/
public void solve(char[][] board) {
int rowSize = board.length,colSize = board[0].length;
boolean [][] visited = new boolean[rowSize][colSize];
//Queue<int []> myQueue = new ArrayDeque<int []>();
Deque<int []> myQueue = new ArrayDeque<int []>();
//Deque<int []> myQueue = new ArrayDeque<int []>();
//先检测,去掉外围四边
for (int row = 0; row < rowSize; row++){
if (board[row][0] == 'O'){
visited[row][0] = true;
myQueue.add(new int[]{row,0});
}
if (board[row][colSize - 1] == 'O'){
visited[row][colSize - 1] = true;
myQueue.add(new int[]{row,colSize- 1});
}
}
for (int col = 1;col < colSize - 1;col++){
if (board[0][col] == 'O'){
visited[0][col] = true;
myQueue.add(new int[]{0,col});
}
if (board[rowSize - 1][col] == 'O'){
visited[rowSize - 1][col] = true;
myQueue.add(new int[]{rowSize - 1,col});
}
}
//---------------------------------------------------------------
while (!myQueue.isEmpty()){
int [] current = myQueue.poll();
for (int [] pos :position){
int row = current[0] + pos[0],col = current[1] + pos[1];
if (row < 0 || row >= rowSize || col < 0 || col >= colSize) continue;
if (visited[row][col] || board[row][col] != 'O') continue;
visited[row][col] = true;
myQueue.add(new int[]{row,col});
}
}
//---------------------------------------------------------------------
for (int row = 0;row < rowSize;row++){
for (int col = 0;col < colSize;col++){
if (board[row][col] == 'O' && !visited[row][col]){
board[row][col] = 'X';
}
}
}
}
}