迷宫问题java深度优先
时间: 2023-12-27 19:04:06 浏览: 115
迷宫深度优先搜索
5星 · 资源好评率100%
以下是一个使用Java深度优先算法解决迷宫问题的示例代码:
```java
import java.util.Stack;
public class MazeSolver {
private int[][] maze;
private int[][] solution;
private int rows; private int cols;
private int startRow;
private int startCol;
private int endRow;
private int endCol;
public MazeSolver(int[][] maze) {
this.maze = maze;
this.rows = maze.length;
this.cols = maze[0].length;
this.solution = new int[rows][cols];
this.startRow = 0;
this.startCol = 0;
this.endRow = rows - 1;
this.endCol = cols - 1;
}
public boolean solveMaze() {
Stack<Cell> stack = new Stack<>();
Cell startCell = new Cell(startRow, startCol);
stack.push(startCell);
while (!stack.isEmpty()) {
Cell currentCell = stack.pop();
int row = currentCell.getRow();
int col = currentCell.getCol();
if (row < 0 || row >= rows || col < 0 || col >= cols) {
continue;
}
if (maze[row][col] == 0 && solution[row][col] == 0) {
solution[row][col] = 1;
if (row == endRow && col == endCol) {
return true;
}
stack.push(new Cell(row + 1, col));
stack.push(new Cell(row - 1, col));
stack.push(new Cell(row, col + 1));
stack.push(new Cell(row, col - 1));
}
}
return false;
}
public void printSolution() {
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
System.out.print(solution[i][j] + " ");
}
System.out.println(); }
}
private class Cell {
private int row;
private int col;
public Cell(int row, int col) {
this.row = row;
this.col = col;
}
public int getRow() {
return row;
}
public int getCol() {
return col;
}
}
}
// 示例用法
int[][] maze = {
{1, 1, 1, 1, 1},
{1, 0, 0, 0, 1},
{1, 1, 1, 0, 1},
{1, 0, 0, 0, 1},
{1, 1, 1, 1, 1}
};
MazeSolver solver = new MazeSolver(maze);
boolean isSolvable = solver.solveMaze();
if (isSolvable) {
System.out.println("The maze is solvable.");
solver.printSolution();
} else {
System.out.println("The maze is not solvable.");
}
```
阅读全文