数据结构与算法之老鼠走迷宫问题


1.

package mouseMazing;

/**
 * @author:孙创
 * @date:2017年3月12日
 * @Discription:老鼠走迷宫 MAZE[i][j]=1;此处有墙,无法通过 MAZE[i][j]=0;此处无墙,可通过
 *                    MAZE[1][1];入口,MAZE[ExitX][ExitY];出口。MAZE[i][j]=2;表示已经走过的路径
 */
public class MouseRunMaze {
	public static int ExitX = 8;// 定义出口x坐标咋第八行
	public static int ExitY = 10;// 定义出口的y坐标再第10列
	public static int[][] MAZE = { { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 },
			{ 1, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1 },
			{ 1, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1 },
			{ 1, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1 },
			{ 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1 },
			{ 1, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1 },
			{ 1, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1 },
			{ 1, 1, 1, 1, 1, 1, 0, 1, 1, 0, 1, 1 },
			{ 1, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1 },
			{ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 } };

	public static void main(String[] args) {
		TraceRecord path = new TraceRecord();
		System.out.println("下图是迷宫的路径:");
		for (int i = 0; i < 10; i++) {
			for (int j = 0; j < 12; j++) {
				System.out.print(MAZE[i][j] + " ");
			}
			System.out.println();
		}

		int x = 1, y = 1;
		while (x <= ExitX && y <= ExitY) {
			// 将走过的路径设为2
			MAZE[x][y] = 2;

			if (MAZE[x - 1][y] == 0) {// 判断向上走
				path.insert(--x, y);
			} else if (MAZE[x + 1][y] == 0) {// 判断向下走
				path.insert(++x, y);
			} else if (MAZE[x][y + 1] == 0) {// 判断向右走
				path.insert(x, ++y);
			} else if (MAZE[x][y - 1] == 0) {// 判断向左走
				path.insert(x, --y);
			} else if (x == ExitX && y == ExitY) {
				break;
			} else {
				x = path.Last.X;
				y = path.Last.Y;
				path.delete();
			}
		}
		// 走到出口
		System.out.println("打印路径(2)");
		for (int i = 0; i < 10; i++) {
			for (int j = 0; j < 12; j++) {
				System.out.print(MAZE[i][j] + " ");
			}
			System.out.println();
		}

	}
}


2.
package mouseMazing;

//用一个链表记录路径
public class TraceRecord {

	public Node First;
	public Node Last;

	/**
	 * 判断节点是否为空
	 * 
	 * @return
	 */
	public boolean isEmpty() {
		return First == null;
	}

	/**
	 * 增加节点
	 * 
	 * @param X
	 * @param Y
	 */
	public void insert(int X, int Y) {
		Node n = new Node(X, Y);
		if (isEmpty()) {
			First = n;
			Last = n;
		} else {
			Last.next = n;
			Last = n;
		}
	}

	/**
	 * 删除节点
	 */
	public void delete() {

		if (isEmpty()) {
			System.out.println("链表已经是空了\n");
		} else {
			Node n = First;
			while (n.next != Last) {
				n = n.next;
			}
			n.next = Last.next;
			Last = n;
		}
	}

	/**
	 * 定义节点的属性
	 * 
	 * @author:孙创
	 * @date:2017年3月12日
	 * @Discription:TODO
	 */
	class Node {
		int X;
		int Y;
		Node next;

		public Node(int X, int Y) {
			this.X = X;
			this.Y = Y;
		}
	}

}


 
  


你可能感兴趣的:(数据结构与算法,堆栈问题,递归)