Java练习数据结构第3章栈和队列——采用队列的迷宫算法

【例 3-22】 采用队列的迷宫算法  页码P61

package hicc.ds.c02_linear2;

import java.util.Arrays;

class Sign {
	int x, y;
	int pre;
	
	@Override
	public String toString() {
		return "(" + x + ", " + y + ", " + pre + ")";
	}
}

public class QueueSolveMaze {
	private int m = 6;
	private int n = 8;
	
	public int path(int[][] maze, Item[] move) {
		Sign[] sq = new Sign[m*n];
		for (int i = 0; i < sq.length; i++) {
			sq[i] = new Sign();
		}
		int front, rear;
		int x, y, i, j, v;
		front = rear = 0;
		sq[0].x = 1;
		sq[0].y = 1;
		sq[0].pre = -1;
		maze[1][1] = -1;
		while (front <= rear) {
			x = sq[front].x;
			y = sq[front].y;
			for (v = 0; v < 8; v++) {
				i = x + move[v].x;
				j = y + move[v].y;
				if (maze[i][j] == 0) {
					rear++;
					sq[rear].x =i;
					sq[rear].y =j;
					sq[rear].pre = front;
					System.out.println(Arrays.toString(sq));
					maze[i][j] = -1;
				}
				if (i == m && j == n) {
					printPath(sq, rear);
					return 1;
				}
			}
			front++;
		}
		return 0;
	}
	
	public void printPath(Sign[] sq, int rear) {
		do {
			System.out.println(sq[rear]);
			rear = sq[rear].pre;
		} while (rear != -1);
	}
	
	public static void main(String[] args) {
		int[][] maze = new int[][] { 
//			  0, 1, 2, 3, 4, 5, 6, 7, 8, 9  
			{ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 }, //0
			{ 1, 0, 1, 1, 1, 0, 1, 1, 1, 1 }, //1
			{ 1, 1, 0, 1, 0, 1, 1, 1, 1, 1 }, //2
			{ 1, 0, 1, 0, 0, 0, 0, 0, 1, 1 }, //3
			{ 1, 0, 1, 1, 1, 0, 1, 1, 1, 1 }, //4
			{ 1, 1, 0, 0, 1, 1, 0, 0, 0, 1 }, //5
			{ 1, 0, 1, 1, 0, 0, 1, 1, 0, 1 }, //6
			{ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 }, //7
		};
		Item[] move = new Item[] { new Item(0, 1), new Item(1, 1), new Item(1, 0), new Item(1, -1), new Item(0, -1),
				new Item(-1, -1), new Item(-1, 0), new Item(-1, 1) };
		QueueSolveMaze queueSolveMaze = new QueueSolveMaze();
		queueSolveMaze.path(maze, move);
	}
}

 

  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值