用Java语言写走迷宫代码
时间: 2023-04-05 22:03:58 浏览: 91
我可以回答这个问题。以下是一个简单的Java代码示例,用于解决迷宫问题:
```
public class MazeSolver {
private int[][] maze;
private boolean[][] visited;
private int startRow, startCol, endRow, endCol;
public MazeSolver(int[][] maze, int startRow, int startCol, int endRow, int endCol) {
this.maze = maze;
this.visited = new boolean[maze.length][maze[0].length];
this.startRow = startRow;
this.startCol = startCol;
this.endRow = endRow;
this.endCol = endCol;
}
public boolean solve() {
return solve(startRow, startCol);
}
private boolean solve(int row, int col) {
if (row < 0 || row >= maze.length || col < 0 || col >= maze[0].length || maze[row][col] == 1 || visited[row][col]) {
return false;
}
visited[row][col] = true;
if (row == endRow && col == endCol) {
return true;
}
if (solve(row - 1, col) || solve(row + 1, col) || solve(row, col - 1) || solve(row, col + 1)) {
return true;
}
return false;
}
}
```
这个代码使用递归算法来解决迷宫问题。它接受一个迷宫数组,起点和终点的行列坐标作为参数,并返回一个布尔值,表示是否找到了一条通路。如果找到了通路,那么visited数组将记录所有已经访问过的位置。