java多线程实现迷宫路径问题
时间: 2023-12-27 16:24:04 浏览: 83
以下是使用Java多线程实现迷宫路径问题的示例代码:
```java
import java.util.ArrayList;
import java.util.List;
public class MazeSolver {
private int[][] maze;
private int startx, starty, endx, endy;
private List<String> paths;
public MazeSolver(int[][] maze, int startx, int starty, int endx, int endy) {
this.maze = maze;
this.startx = startx;
this.starty = starty;
this.endx = endx;
this.endy = endy;
this.paths = new ArrayList<>();
}
public void solve() {
solveMaze(startx, starty, "");
}
private void solveMaze(int x, int y, String path) {
if (x < 0 || y < 0 || x >= maze.length || y >= maze[0].length || maze[x][y] == 1) {
return;
}
if (x == endx && y == endy) {
paths.add(path);
return;
}
maze[x][y] = 1;
Thread t1 = new Thread(() -> solveMaze(x + 1, y, path + "D"));
Thread t2 = new Thread(() -> solveMaze(x - 1, y, path + "U"));
Thread t3 = new Thread(() -> solveMaze(x, y + 1, path + "R"));
Thread t4 = new Thread(() -> solveMaze(x, y - 1, path + "L"));
t1.start();
t2.start();
t3.start();
t4.start();
try {
t1.join();
t2.join();
t3.join();
t4.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
maze[x][y] = 0;
}
public List<String> getPaths() {
return paths;
}
}
```
使用示例:
```java
public class Main {
public static void main(String[] args) {
int[][] maze = {
{0, 0, 0, 0, 0},
{1, 1, 0, 1, 1},
{0, 0, 0, 0, 0},
{0, 1, 1, 1, 0},
{0, 0, 0, 0, 0}
};
int startx = 0;
int starty = 0;
int endx = 4;
int endy = 4;
MazeSolver solver = new MazeSolver(maze, startx, starty, endx, endy);
solver.solve();
List<String> paths = solver.getPaths();
for (String path : paths) {
System.out.println(path);
}
}
}
```
这段代码使用了多线程来实现迷宫路径问题的解决。每个线程代表一个方向(上、下、左、右),通过递归调用solveMaze方法来搜索路径。当找到终点时,将路径添加到列表中。最后,打印出所有找到的路径。
阅读全文