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 1
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)-(3,1)-(3,2)-(2,2)-(2,3)-(3,3)
找到路线:(0,0)-(0,1)-(1,1)-(2,1)-(2,2)-(3,2)-(3,3)
找到路线:(0,0)-(0,1)-(1,1)-(2,1)-(2,2)-(2,3)-(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,3)-(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,3)-(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)-(3,1)-(3,2)-(2,2)-(2,3)-(3,3)
找到路线:(0,0)-(0,1)-(0,2)-(1,2)-(1,1)-(2,1)-(2,2)-(3,2)-(3,3)
找到路线:(0,0)-(0,1)-(0,2)-(1,2)-(1,1)-(2,1)-(2,2)-(2,3)-(3,3)
最短路线为:(0,0)-(0,1)-(1,1)-(2,1)-(3,1)-(3,2)-(3,3)

 

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

2018.8.8:修复代码中使用全局变量时由于资源竞争导致的bug。

 

 

import java.util.Scanner;

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

	public static void main(String[] args) {
		int[][] t = {
			{1,1,1,1},
			{0,1,1,0},
			{1,1,1,1},
			{0,1,1,1}
		};

		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, String s) {
		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 += "(" + x + "," + y + ")";
			if (smin.length() == 0 || smin.length() > s.length())
				smin = s;
			System.out.println("找到路线:" + s);
			return;
		}
		String temp = s;
		s += "(" + x + "," + y + ")" + "-"; // 记录路线
		mk[x][y] = 1; // 将走过的路标记
		// 向四个方向搜索
		dfs(x + 1, y, t, s);
		dfs(x, y + 1, t, s);
		dfs(x, y - 1, t, s);
		dfs(x - 1, y, t, s);
		// 		将路线和标记恢复成上一次的状态
		mk[x][y] = 0;
		s = temp;
	}

}

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

 

 

 

    原文作者:迷宫问题
    原文地址: https://blog.csdn.net/sdzhr/article/details/63692087
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞