//error
import java.util.*;
public class Solution {
public static void solve(char[][] board) {
if (board.length == 0) {
return;
}
for (int i = 0; i < board.length; i++) {
for (int j = 0; j < board[0].length; j++) {
if (i == 0 || i == board.length - 1 || j == 0 || j == board[0].length - 1) {
if (board[i][j] == 'O') {
List<Integer> list = new ArrayList<>(2);
list.add(i);
list.add(j);
BFS(list, board);
}
}
}
}
for (int i = 0; i < board.length; i++) {
for (int j = 0; j < board[0].length; j++) {
if (board[i][j] == '*') {
board[i][j] = 'O';
} else if (board[i][j] == 'O') {
board[i][j] = 'X';
}
}
}
}
public static int aX[] = {0, 0, -1, 1};
public static int aY[] = {1, -1, 0, 0};
public static void BFS(List<Integer> list, char[][] board) {
Queue<List<Integer>> queue = new LinkedList();
queue.add(list);
while (!queue.isEmpty()) {
List<Integer> listTemp = queue.poll();
int i = listTemp.get(0);
int j = listTemp.get(1);
board[i][j] = '*';
for (int q = 0; q < 4; q++) {
int tempX = i + aX[q];
int tempY = j + aY[q];
//System.out.println(tempX+"&"+tempY);
if (tempX < 0 || tempX > board.length - 1 || tempY < 0 || tempY > board[0].length - 1) {
continue;
}
if (board[tempX][tempY] == 'O') {
List<Integer> tempList = new ArrayList(2);
tempList.add(tempX);
tempList.add(tempY);
queue.offer(tempList);
}
}
}
}
}
//correct
//在加入队列之前visited=true
import java.util.*;
public class Solution {
public static void solve(char[][] board) {
if (board.length == 0) {
return;
}
for (int i = 0; i < board.length; i++) {
for (int j = 0; j < board[0].length; j++) {
if (i == 0 || i == board.length - 1 || j == 0 || j == board[0].length - 1) {
if(board[i][j]=='O')
{
List<Integer> list = new ArrayList<>(2);
list.add(i);
list.add(j);
board[i][j] = '*';
bfs(list,board);
}
}
}
}
for (int i = 0; i < board.length; i++) {
for (int j = 0; j < board[0].length; j++) {
if (board[i][j] == '*') {
board[i][j] = 'O';
} else if (board[i][j] == 'O') {
board[i][j] = 'X';
}
}
}
}
public static int aX[] = {0, 0, -1, 1};
public static int aY[] = {1, -1, 0, 0};
public static void bfs(List<Integer> list,char [][]board)
{
Queue<List<Integer>> queue = new LinkedList();
queue.add(list);
while (!queue.isEmpty()) {
List<Integer> listTemp = queue.poll();
int tempI = listTemp.get(0);
int tempJ = listTemp.get(1);
for (int q = 0; q < 4; q++) {
int tempX = tempI + aX[q];
int tempY = tempJ + aY[q];
//System.out.println(tempX+"&"+tempY);
if (tempX < 0 || tempX > board.length - 1 || tempY < 0 || tempY > board[0].length - 1) {
continue;
}
if (board[tempX][tempY] == 'O') {
board[tempX][tempY] = '*';
List<Integer> tempList = new ArrayList(2);
tempList.add(tempX);
tempList.add(tempY);
queue.offer(tempList);
}
}
}
}
}
BFS都能写错!!!
最新推荐文章于 2024-04-10 17:40:29 发布