public class Step {
int x, y, d;
public Step(int x, int y, int d) {
this.x = x;// 横坐标
this.y = y;// 纵坐标
this.d = d;// 方向
}
public boolean equals(Step obj) {
if (x != obj.x)
return false;
if (y != obj.y)
return false;
return true;
}
public static void main(String[] args) {
// 迷宫定义
int[][] maze = { { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 },
{ 1, 0, 1, 1, 1, 0, 1, 1, 1, 1 },
{ 1, 1, 0, 1, 0, 1, 1, 1, 1, 1 },
{ 1, 0, 1, 0, 0, 0, 0, 0, 1, 1 },
{ 1, 0, 1, 1, 1, 0, 1, 1, 1, 1 },
{ 1, 1, 0, 0, 1, 1, 0, 0, 0, 1 },
{ 1, 0, 1, 1, 0, 0, 1, 1, 0, 1 },
{ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 } };
int[][] move = { { 0, 1 }, { 1, 1 }, { 1, 0 }, { 1, -1 }, { 0, -1 },
{ -1, -1 }, { -1, 0 }, { -1, 1 } };
Stack<Step> s = new Stack<Step>();
int i=path(s, new Step(1,1,-1), new Step(6,8,1), maze, move);
System.out.println(i);
while (!s.isEmpty()) {
Step a = s.pop();
System.out.println("step.x=" + a.x + ",step.y=" + a.y);
}
}
public static int path(Stack<Step> s, Step beg, Step end, int[][] maze,
int[][] move) {
s.push(beg);
while (!s.isEmpty()) {
Step tmp = s.pop();
int x = tmp.x;
int y = tmp.y;
int d = tmp.d + 1;
while (d < 8) {
int i = x + move[d][0];
int j = y + move[d][1];
if (maze[i][j] == 0) {
tmp = new Step(i, j, d); // 到达新点
s.push(tmp);
x = i;
y = j;
maze[x][y] = -1; // 到达新点,标志已经到达
if(tmp.equals(end)){
return 1;
}else{
d=0;
}
}else{
d++;
}
}
}
return 0;
}
}
java走迷宫
最新推荐文章于 2021-09-10 18:54:21 发布