第一次在Stack上发帖,如果格式或其他内容不正确,我们深感抱歉。
我只是不确定如何将访问的单元格添加到队列中,因为我发现没有任何效果。我想念什么吗?
我正在尝试实现类似于BFS
算法的方法。
这是我的代码:
import java.io.*;
import java.util.*;
public class mazeSolver {
public static class Cell {
int row;
int col;
Cell(int row, int col) {
this.row = row;
this.col = col;
}
public int getRow() {
return this.row;
}
public int getCol() {
return this.col;
}
}
static char[][] grid;
static boolean[][] visited;
static int[][] d;
static int n;
static Cell A;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
n = sc.nextInt();
grid = new char[n][n];
visited = new boolean[n][n];
d = new int[n][n];
String row;
for (int i = 0; i < n; i++) {
row = sc.next();
for (int j = 0; j < n; j++) {
grid[i][j] = row.charAt(j);
if (grid[i][j] == 'A') {
A = new Cell(i, j);
}
}
}
sc.close();
int distance = solve();
if (distance == -1) {
System.out.println("IMPOSSIBLE");
} else {
System.out.println(distance);
}
}
static boolean isCellValid(Cell cell) {
if(cell.getRow()<0||cell.getRow()>=n)
return false;
if(cell.getCol()<0||cell.getCol()>=n)
return false;
if(grid[cell.getRow()][cell.getCol()]=='#')
return false;
return true;
}
public static int solve() {
Queue<Cell> q = new ArrayDeque<>();
q.add(A);
d[A.getRow()][A.getCol()] = 0;
visited[A.getRow()][A.getCol()] = true;
while (!q.isEmpty()) {
Cell currentCell = q.remove();
int row = currentCell.getRow();
int col = currentCell.getCol();
if (grid[row][col] == 'B')
return d[row][col];
else {
// moving left
if (col - 1 >= 0 && visited[row][col - 1] == false) {
visited[row][col - 1] = true;
d[row][col] = d[currentCell.row][currentCell.col]+1;
//q.add(Cell(d[row][col] + 1));
}
// moving right
if (col + 1 < n && visited[row][col + 1] == false) {
visited[row][col + 1] = true;
d[row][col] = d[currentCell.row][currentCell.col]+1;
//q.add(Cell(d[row][col] + 1));
}
// moving up
if (row - 1 >= 0 && visited[row - 1][col] == false) {
visited[row - 1][col] = true;
d[row][col] = d[currentCell.row][currentCell.col] + 1;
//q.add(Cell(d[A.getRow()][A.getCol()] + 1));
}
// moving down
if (row + 1 < n && visited[row + 1][col] == false) {
visited[row + 1][col] = true;
d[row][col] = d[currentCell.row][currentCell.col] + 1;
//q.add();
}
//return d[row][col];
}
}
return -1;
}
}