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

来源:互联网 发布:2017年各月m2数据 编辑:程序博客网 时间:2024/05/16 09:11

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

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 stubScanner 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 stubint[][] 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
原创粉丝点击