java走迷宫

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;
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值