用栈实现迷宫数据结构java
时间: 2023-11-26 08:43:26 浏览: 38
可以使用栈来实现迷宫数据结构。下面是一个示例的 Java 代码:
```java
import java.util.Stack;
public class Maze {
private int[][] maze;
private int rows;
private int cols;
public Maze(int[][] maze) {
this.maze = maze;
this.rows = maze.length;
this.cols = maze[0].length;
}
public boolean isPath(int startX, int startY, int endX, int endY) {
Stack<int[]> stack = new Stack<>();
boolean[][] visited = new boolean[rows][cols];
stack.push(new int[]{startX, startY});
while (!stack.isEmpty()) {
int[] current = stack.pop();
int x = current[0];
int y = current[1];
if (x == endX && y == endY) {
return true;
}
if (isValid(x, y) && !visited[x][y] && maze[x][y] == 0) {
visited[x][y] = true;
stack.push(new int[]{x - 1, y}); // 上
stack.push(new int[]{x + 1, y}); // 下
stack.push(new int[]{x, y - 1}); // 左
stack.push(new int[]{x, y + 1}); // 右
}
}
return false;
}
private boolean isValid(int x, int y) {
return x >= 0 && x < rows && y >= 0 && y < cols;
}
}
```
使用示例:
```java
int[][] mazeData = {
{0, 1, 0, 0},
{0, 0, 0, 1},
{0, 1, 0, 0},
{0, 1, 0, 0}
};
Maze maze = new Maze(mazeData);
int startX = 0;
int startY = 0;
int endX = 3;
int endY = 3;
boolean isPathExists = maze.isPath(startX, startY, endX, endY);
System.out.println("是否存在路径: " + isPathExists);
```