java递归实现迷宫算法

描述:已知迷宫入口和出口位置,数组中0代表可以通过,1代表墙,求入口到出口的最短路程。

此程序会打印出所有可能的路径,并且打印最短路径的步数。

import java.util.LinkedList;
public class MG {
	static int min = Integer.MAX_VALUE; // 记录最小的步数
	static int endX = 3, endY = 3; // 出口位置
	static int width = 5, height = 4; // 迷宫的宽度和高度
	static int[][] maze = new int[5][4]; // 迷宫数组
	static int[][] mark = new int[5][4]; // 路径标记
	static LinkedList<Integer> map = new LinkedList<>();
	public static void dfs(int startX, int startY, int step) {
		int[][] next = new int[][] { { 1, 0 }, { 0, 1 }, { -1, 0 }, { 0, -1 } };  //四个方向
		int nextX, nextY; // 下一步要走的位置
		int position; // 控制走的方向

                //判断该位置是否为终点
		if (startX == endX && startY == endY) {
			// 到达终点,保留最小的步数
			if (step < min)
				min = step;
			// 打印路径
			for (int i = map.size() - 1; i >= 0; i -= 2) {
				nextX = map.get(i);
				nextY = map.get(i - 1);
				System.out.print("(" + nextX + "," + nextY + ")");
				if (i != 1)
					System.out.print(" ");
			}
			System.out.println();
			return;
		}
		// 若没到终点,则判断其周围是否有通道
		for (position = 0; position < next.length; position++) {
			nextX = startX + next[position][0];
			nextY = startY + next[position][1];
			// 判断坐标是否超出界限
			if (nextX < 0 || nextX >= width || nextY < 0 || nextY >= height)
				continue;
			// 未超出界限,判断该位置是否为0,且未被访问
			if (maze[nextX][nextY] == 0 && mark[nextX][nextY] == 0) {
				map.push(startX); // 将上一个位置保存
				map.push(startY);
				mark[nextX][nextY] = 1; // 将该位置设置为已访问
				dfs(nextX, nextY, step + 1); // 递归移动到下一个
				mark[nextX][nextY] = 0;    //回溯到上一个位置,并还原其值
				map.pop();
				map.pop();
			}
		}
	}


	public static void main(String[] args) {
		int startX=0,startY=0;  //初始位置
		MG m = new MG();
		//初始化迷宫
		maze = new int[width][height];
		mark = new int[width][height];
		maze[1][2]=1;
		maze[2][2]=1;
		maze[3][2]=1;
		maze[2][0]=1;
		maze[0][0]=1;
		dfs(startX,startY,0);
		if(min<Integer.MAX_VALUE)
			System.out.println("至少需要"+min+"步");
		else
			System.out.println("目标无法到达");
	}
}

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值