java走迷宫

来源:互联网 发布:手机怎么绑定淘宝 编辑:程序博客网 时间:2024/05/22 00:05
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;}}

0 0
原创粉丝点击