java程序走矩阵迷宫

阅读更多
import java.util.Arrays;
import java.util.Stack;

/**
 * 迷宫
 * 
 * @author 风华褚胜
 */
public class MiGong {

	public static void main(String[] args) {
		Stack stack = new Stack(); // 保存迷宫路径
		Stack end = new Stack();// 保存可通路路径
		new MiGong().f(getMiGong(), 1, 1/* 是起始坐标 */, 8, 8/* 是终点坐标 */,
				0/* 上一步的方向 */, stack, end);

		int shor = Integer.MAX_VALUE;
		int index = 0;
		for (int i = 0; i < end.size(); i++) {
			if (shor > end.get(i).length) {
				index = i;
				shor = end.get(i).length;
			}
		}

		if (end.size() != 0) {
			System.out.println("最短路径:");
			System.out.println(Arrays.toString(end.get(index)));
		} else
			System.out.println("无通路");
	}

	public static int[][] getMiGong() {
		// int[][] num = { { 1, 1, 1, 1, 1 },
		// { 1, 0, 1, 1, 1 },
		// { 1, 0, 1, 1, 1 },
		// { 1, 0, 0, 0, 1 },
		// { 1, 1, 0, 0, 1 },
		// { 1, 1, 1, 1, 1 } };
		int[][] num = { { 1, 1, 1, 1, 1, 1, 1, 1, 1 },
				{ 1, 0, 0, 0, 0, 0, 0, 0, 1 }, { 1, 0, 1, 1, 0, 1, 1, 0, 1 },
				{ 1, 0, 1, 0, 0, 1, 0, 0, 1 }, { 1, 0, 1, 0, 1, 0, 1, 0, 1 },
				{ 1, 0, 0, 0, 0, 0, 1, 0, 1 }, { 1, 1, 0, 1, 1, 0, 1, 1, 1 },
				{ 1, 0, 0, 0, 0, 0, 0, 0, 1 }, { 1, 1, 1, 1, 1, 1, 1, 1, 1 } };
		return num;
	}

	/**
	 * 求取所有路径
	 * 
	 * @param num
	 *            迷宫矩阵
	 * @param start_row
	 *            开始坐标x
	 * @param start_col
	 *            开始坐标y
	 * @param end_row
	 *            结束坐标x
	 * @param end_col
	 *            结束坐标y
	 * @param dro
	 *            上一步走的方向
	 * @param s
	 *            保存迷宫路径
	 * @param end
	 *            保存可通路路径
	 */
	public void f(int[][] num, int start_row, int start_col, int end_row,
			int end_col, int dro, Stack s, Stack end) {
		// System.out.println(Arrays.toString(s.toArray()));

		s.push(new Position(start_row, start_col));
		if (start_row == end_row && start_col == end_col) {
			System.out.println(Arrays.toString(s.toArray()));
			end.push(s.toArray());
			s.pop();
			return;
		}
		num[start_row][start_col] = 1;
		if (dro != 2 && num[start_row - 1][start_col] == 0) {
			f(num, start_row - 1, start_col, end_row, end_col, 1, s, end);
		}
		if (dro != 1 && num[start_row + 1][start_col] == 0) {
			f(num, start_row + 1, start_col, end_row, end_col, 2, s, end);
		}
		if (dro != 4 && num[start_row][start_col - 1] == 0) {
			f(num, start_row, start_col - 1, end_row, end_col, 3, s, end);
		}
		if (dro != 3 && num[start_row][start_col + 1] == 0) {
			f(num, start_row, start_col + 1, end_row, end_col, 4, s, end);
		}
		num[start_row][start_col] = 0;
		s.pop();
		return;
	}

	/**
	 * 坐标点的表示类
	 * 
	 * @author 风华褚胜
	 */
	class Position {
		public int row;
		public int col;

		public Position(int row, int col) {
			this.row = row;
			this.col = col;
		}

		@Override
		public String toString() {
			return "(" + row + "," + col + ")";
		}
	}
}

你可能感兴趣的:(java,迷宫,递归,矩阵)