深度优先搜索实现迷宫的走法

从起点走到指点的迷宫坐标输出最短的步数!最短路径吧!

import java.util.Scanner;

/*
 * 结合DFS实现的 迷宫走法
 * 
 * */
public class migong {
	static int p;// 终点x坐标
	static int q;// 终点y坐标
	static int startx;// 起点x坐标
	static int starty;// 起点y左边
	static int[][] book;// 标记数组,用来记录是否已经访问过该坐标
	static int n;
	static int m;
	static int[][] a;
	static int min = 99999999;

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Scanner sc = new Scanner(System.in);
		n = sc.nextInt();
		m = sc.nextInt();
		a = new int[51][51];
		book = new int[51][51];
		for (int i = 1; i <= n; i++) {// 读入数组,舍弃0行0列 角标,从第一行第一列角标开始 读入数组中
			for (int j = 1; j <= m; j++) {
				a[i][j] = sc.nextInt();
			}
		}
		// sop(a, m, n);
		startx = sc.nextInt();
		starty = sc.nextInt();
		p = sc.nextInt();
		q = sc.nextInt();
		book[startx][starty] = 1;// 初始化起点为1,表示已经访问过了。
		dfs(startx, starty, 0);
		System.out.println(min);
	}

	private static void dfs(int x, int y, int step) {
		// TODO Auto-generated method stub
		int[][] next = new int[][] { // 用数组判断方向
				{ 0, 1 }, // 向右
				{ 1, 0 }, // 向下
				{ 0, -1 }, // 向左
				{ -1, 0 },// 向上
		};

		if (x == p && y == q) {// 判断是否已经找到终点
			if (step < min)
				min = step;
			return;
		}
		int tx, ty;
		// 枚举四种走法
		for (int k = 0; k <= 3; k++) {
			// 计算下一个点的坐标
			tx = x + next[k][0];
			ty = y + next[k][1];
			// 判断是否越界
			if (tx < 1 || tx > n || ty < 1 || ty > m) {

				continue;
			}
			if (a[tx][ty] == 0 && book[tx][ty] == 0) {
				book[tx][ty] = 1;
				dfs(tx, ty, step + 1);
				book[tx][ty] = 0;
			}
		}

	}

}
第一行有两个数  n m , n表示迷宫的行 ,m表示迷宫的列。

接下来n行 m列 为迷宫。 0 表示空地,1表示障碍物。最后一行4个数 ,前

两个数为迷宫的入口x和y坐标。最后两个数为终点的x和y坐标!
输入数据

5 4

0 0 1 0

0 0 0 0

0 0 1 0

0 1 0 0

0 0 0 1

1 1 4 3

输出

7


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值