DFS算法之迷宫寻路问题

要求输入两个整数m,n表示迷宫矩阵大小(m*n),然后输入迷宫矩阵,0表示死路,1表示通路。令迷宫入口坐标为(0,0)出口坐标为(m-1,n-1)。

要求输出走出迷宫的所有路线和最短的一条路线。

如:

输入

4 4
1 1 1 1
0 1 1 0
1 1 1 0
0 1 1 1

则输出

找到路线:(0,0)-(0,1)-(1,1)-(2,1)-(3,1)-(3,2)-(3,3)
找到路线:(0,0)-(0,1)-(1,1)-(2,1)-(2,2)-(3,2)-(3,3)
找到路线:(0,0)-(0,1)-(1,1)-(1,2)-(2,2)-(3,2)-(3,3)
找到路线:(0,0)-(0,1)-(1,1)-(1,2)-(2,2)-(2,1)-(3,1)-(3,2)-(3,3)
找到路线:(0,0)-(0,1)-(0,2)-(1,2)-(2,2)-(3,2)-(3,3)
找到路线:(0,0)-(0,1)-(0,2)-(1,2)-(2,2)-(2,1)-(3,1)-(3,2)-(3,3)
找到路线:(0,0)-(0,1)-(0,2)-(1,2)-(1,1)-(2,1)-(3,1)-(3,2)-(3,3)
找到路线:(0,0)-(0,1)-(0,2)-(1,2)-(1,1)-(2,1)-(2,2)-(3,2)-(3,3)
最短路线为:(0,0)-(0,1)-(1,1)-(2,1)-(3,1)-(3,2)-(3,3)


ps:以上题目要求纯属我自己yy,,,如有雷同纯属巧合。


import java.util.Scanner;

//dfs走迷宫
public class Main {
	static int[][] mk = new int[100][100];
	static int m;
	static int n;
	static String s = "";
	static String smin = "";

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		m = sc.nextInt();
		n = sc.nextInt();
		int[][] t = new int[m][n];

		for (int i = 0; i < m; i++) {
			for (int j = 0; j < n; j++) {
				t[i][j] = sc.nextInt();
			}
		}
		dfs(0, 0, t);
		if (smin.length() != 0)
			System.out.println("最短路线为:" + smin);
		else
			System.out.println("没有找到路线!");
	}

	public static void dfs(int x, int y, int[][] t) {
		if (x < 0 || y < 0)
			return;
		if (x > m - 1 || y > m - 1 || mk[x][y] != 0)
			return;
		if (t[x][y] == 0)
			return; // 判断是否通路和越界
		if (x == m - 1 && y == n - 1) { // 判断是否抵达出口
			s = s + "(" + x + "," + y + ")";
			if (smin.length() == 0 || smin.length() > s.length())
				smin = s;
			System.out.println("找到路线:" + s);
			return;
		}
		String temp = s;
		s = s + "(" + x + "," + y + ")" + "-"; // 记录路线
		mk[x][y] = 1; // 将走过的路标记
		// 向四个方向搜索
		dfs(x + 1, y, t);
		dfs(x, y + 1, t);
		dfs(x, y - 1, t);
		dfs(x - 1, y, t);
		// 将路线和标记恢复成上一次的状态
		mk[x][y] = 0;
		s = temp;
	}

}

笔记:因为是递归调用所以一定要理解先进后出的原则。

猜你喜欢

转载自blog.csdn.net/sdzhr/article/details/63692087