迷宫寻路
给出起始位置找出一条存在的路线到达指定的位置
借助栈来实现回溯算法
如果要寻找最短路径会更加麻烦些
回溯算法的流程
import java.util.Objects;
import java.util.Stack;
public class Test_traceback {
boolean[][] map = new boolean[6][6];
int[][] board = {
{1, 1, 1, 1, 1, 1},
{1, 0, 1, 1, 0, 1},
{1, 0, 0, 0, 0, 1},
{1, 0, 1, 1, 1, 1},
{1, 0, 0, 0, 0, 1},
{1, 1, 1, 1, 1, 1}};
Point startP;
Point endP;
Test_traceback(int startX, int startY, int endX, int endY) {
for (int i = 0; i < 6; i++) {
for (int j = 0; j < 6; j++) {
map[i][j] = (board[i][j] == 0);
}
}
startP = new Point(startX, startY);
endP = new Point(endX, endY);
}
public class Point {
public int row;
public int col;
public char direction;
Point(int row, int col) {
this.row = row;
this.col = col;
direction = 'W';
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Point point = (Point) o;
return row == point.row && col == point.col;
}
@Override
public String toString() {
return "Point{" +
"row=" + row +
", col=" + col +
", direction=" + direction +
'}';
}
}
public void traceback() throws InterruptedException {
Stack<Point> s = new Stack<>();
Point currentP = startP;
s.push(startP);
char direction = 'W'; //WASD 上左下右
while (!endP.equals(currentP)) {
switch (currentP.direction) {
case 'W': //如果不包含新方向的点就加入,如果已经存在了,则换个方向?还是弹出?
if (map[currentP.row - 1][currentP.col]) {
Point p = new Point(currentP.row - 1, currentP.col);
if (!s.contains(p)) {
s.push(p);
currentP.direction = 'D';
break;
}
}
currentP.direction = 'D';
case 'D':
if (map[currentP.row][currentP.col + 1]) {
Point p = new Point(currentP.row, currentP.col + 1);
if (!s.contains(p)) {
s.push(p);
currentP.direction = 'S';
break;
}
}
currentP.direction = 'S';
case 'S':
if (map[currentP.row + 1][currentP.col]) {
Point p = new Point(currentP.row + 1, currentP.col);
if (!s.contains(p)) {
s.push(p);
currentP.direction = 'A';
break;
}
}
currentP.direction = 'A';
case 'A'://'A'
if (map[currentP.row][currentP.col - 1]) {
Point p = new Point(currentP.row, currentP.col - 1);
if (!s.contains(p)) { //最后的方向了
s.push(p);
break;
}//所有的方向都已经尝试过了
}
if (s.size() > 1) {
s.pop();
}else {
return;
}
}
currentP = s.peek();
System.out.println(s.size() + " " + currentP.toString());
}
}
public static void main(String[] args) throws InterruptedException {
Test_traceback test = new Test_traceback(1, 1, 4, 4);
test.traceback();
}
}
输出结果: