java通过txt读取迷宫地图_java寻找迷宫路径的简单实现示例
时间: 2024-02-02 17:04:16 浏览: 88
好的,以下是一个简单的 Java 程序,可以通过读取 txt 文件中的迷宫地图,然后寻找迷宫路径:
```java
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class MazeSolver {
private static final int WALL = 1;
private static final int PATH = 0;
private static final int VISITED = 2;
private int[][] maze;
private int startRow, startCol;
private int endRow, endCol;
public MazeSolver(String filename) throws IOException {
// 从文件中读取迷宫地图
BufferedReader br = new BufferedReader(new FileReader(filename));
String line;
int row = 0;
while ((line = br.readLine()) != null) {
if (maze == null) {
maze = new int[line.length()][line.length()];
}
for (int col = 0; col < line.length(); col++) {
char c = line.charAt(col);
if (c == '#') {
maze[row][col] = WALL;
} else if (c == 'S') {
startRow = row;
startCol = col;
maze[row][col] = PATH;
} else if (c == 'E') {
endRow = row;
endCol = col;
maze[row][col] = PATH;
} else {
maze[row][col] = PATH;
}
}
row++;
}
br.close();
}
public void solve() {
if (findPath(startRow, startCol)) {
System.out.println("Found path!");
printMaze();
} else {
System.out.println("No path found!");
}
}
private boolean findPath(int row, int col) {
if (row < 0 || row >= maze.length || col < 0 || col >= maze[0].length) {
return false;
}
if (maze[row][col] == WALL || maze[row][col] == VISITED) {
return false;
}
if (row == endRow && col == endCol) {
return true;
}
maze[row][col] = VISITED;
if (findPath(row - 1, col) || findPath(row + 1, col) || findPath(row, col - 1) || findPath(row, col + 1)) {
return true;
}
maze[row][col] = PATH;
return false;
}
private void printMaze() {
for (int row = 0; row < maze.length; row++) {
for (int col = 0; col < maze[0].length; col++) {
if (maze[row][col] == WALL) {
System.out.print("#");
} else if (maze[row][col] == PATH) {
System.out.print(".");
} else if (maze[row][col] == VISITED) {
System.out.print("X");
}
}
System.out.println();
}
}
public static void main(String[] args) {
try {
MazeSolver solver = new MazeSolver("maze.txt");
solver.solve();
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
在上面的程序中,我们通过 `BufferedReader` 读取了一个 txt 文件(文件名为 `maze.txt`),然后将其转换成一个二维数组 `maze` 表示迷宫地图。在地图中,`#` 表示墙壁,`.` 表示通路,`S` 表示起点,`E` 表示终点。然后我们使用递归函数 `findPath` 来寻找迷宫路径。如果递归到了终点,返回 `true`,表示找到了路径;否则返回 `false`。在递归过程中,我们用 `maze` 数组来记录哪些格子是墙壁,哪些格子已经走过,哪些格子是通路。
最后,我们在 `main` 函数中创建了一个 `MazeSolver` 对象,并调用其 `solve` 方法来解决迷宫问题。
阅读全文
相关推荐















