迷宫问题 --- 回溯法

迷宫问题

定义一个二维数组N*M(其中2<=N<=10;2<=M<=10),如5 × 5数组下所示:

int maze[5][5] = {
0, 1, 0, 0, 0,
0, 1, 0, 1, 0,
0, 0, 0, 0, 0,
0, 1, 1, 1, 0,
0, 0, 0, 1, 0,
};

它表示一个迷宫,其中的1表示墙壁,0表示可以走的路,只能横着走或竖着走,不能斜着走,要求编程序找出从左上角到右下角的最短路线。入口点为[0,0],既第一空格是可以走的路。

本题含有多组数据。

输入描述:
输入两个整数,分别表示二位数组的行数,列数。再输入相应的数组,其中的1表示墙壁,0表示可以走的路。数据保证有唯一解,不考虑有多解的情况,即迷宫只有一条通道。

输出描述:
左上角到右下角的最短路径,格式如样例所示。

示例1
输入
5 5
0 1 0 0 0
0 1 0 1 0
0 0 0 0 0
0 1 1 1 0
0 0 0 1 0
输出
(0,0)
(1,0)
(2,0)
(2,1)
(2,2)
(2,3)
(2,4)
(3,4)
(4,4)

链接:https://www.nowcoder.com/questionTerminal/cf24906056f4488c9ddb132f317e03bc
来源:牛客网

思路

我认为回溯法求最小路径长度不是难点,难点在于怎么记录下每个走过节点的位置信息,我是用栈(因为栈不好复制,也就是深拷贝,所以我采用list来充当栈的角色)来在递归中加入i,j的位置,然后在到达终点时,把栈终所有位置信息拷贝到另一个list中来记录每次到重点的所有位置信息,最后只需要找到最小路径长度的那个list位置信息进行打印输出即可。

每步代码都有解析,可以参考

代码

import java.util.*;

public class Main {
    public static int min = Integer.MAX_VALUE;  //到达长点最小步骤
    public static List<int[]> stack = null; //用链表代替栈的功能
    public static List<List<int[]>> list = null; //链表存放能到达终点的所有路径
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNext()) {
            int n = scanner.nextInt();
            int m = scanner.nextInt();
            int[][] map = new int[n][m];
            for (int i = 0; i < map.length; i++) {
                for (int j = 0; j < map[0].length; j++) {
                    map[i][j] = scanner.nextInt();
                }
            }
            boolean[][] isUsed = new boolean[n][m]; //判断该节点是否走过
            int count = 1;  //计走的步数
            stack = new ArrayList<>();  //实例化
            list = new ArrayList<>();   //实例化
            dfs(0,0,map,isUsed,count);  //调用函数,深度优先遍历
            int minStep = Integer.MAX_VALUE;    //最小步数
            List<int[]> res = null;     //最小步数的所有节点
            for (int i = 0; i < list.size(); i++) {
                if (list.get(i).size() < minStep) {
                    minStep = list.get(i).size();
                    res = list.get(i);
                }
            }
            //打印所有步数
            for (int i = 0; i < res.size(); i++) {
                System.out.println("(" + res.get(i)[0] + "," + res.get(i)[1] + ")");
            }
        }
    }

    //回溯法
    public static void dfs(int i, int j, int[][] map, boolean[][] isUsed,int count) {
        stack.add(new int[]{i,j});  //每次递归进来都给栈加i,j位置
        //如果到达了终点,则把之前的所有步位置放到list保存
        if (i == map.length-1 && j == map[0].length-1) {
            List<int[]> res = new ArrayList<>(stack);
            list.add(res);
            if (count < min) {
                min = count;
            }
            return; //这里回溯,因为有可能不是最小步数
        }
        isUsed[i][j] = true;    //该位置变为走过
        //分别在上下左右进行递归,下一步的位置不能越界,不能走过,不能是墙
        //上
        if (i-1 < map.length && i-1 >= 0 && !isUsed[i-1][j] && map[i-1][j] == 0) {
            dfs(i-1,j,map,isUsed,count+1);
        }
        //下
        if (i + 1 < map.length && !isUsed[i + 1][j] && map[i+1][j] == 0) {
            dfs(i+1,j,map,isUsed,count+1);
        }
        //左
        if (j-1 < map[0].length && j-1 >= 0 && !isUsed[i][j-1] && map[i][j-1] == 0) {
            dfs(i,j-1,map,isUsed,count+1);
        }
        //右
        if (j + 1 < map[0].length && !isUsed[i][j + 1] && map[i][j+1] == 0) {
            dfs(i,j+1,map,isUsed,count+1);
        }
        isUsed[i][j] = false;   //回溯后要给走过位置置为为走过
        stack.remove(stack.size()-1);   //回溯后要给出栈
    }
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
回溯法可以用来解决迷宫问题。假设有一个 n x n 的迷宫,其中起点为 (start_x, start_y),终点为 (end_x, end_y),墙壁用 1 表示,可通行的路用 0 表示。我们需要找到一条从起点到终点的路径。 回溯法的基本思路是从起点开始,依次尝试向上、向下、向左、向右走,如果能够走通,则继续往前走,直到到达终点或者无路可走,如果无路可走,则回溯到上一个节点,重新尝试其他方向。 具体实现可以使用递归函数来完成。函数参数包括当前位置 (x, y) 和已经走过的路径 path。在递归函数中,首先判断当前位置是否为终点,如果是,则返回已经走过的路径;否则,依次尝试向上、向下、向左、向右走,如果能够走通,则递归进入下一个节点,如果不行,则回溯到上一个节点。 以下是一个 Python 实现的回溯法迷宫问题求解代码: ```python def solve_maze(maze, start_x, start_y, end_x, end_y, path): # 判断当前位置是否为终点 if start_x == end_x and start_y == end_y: return path + [(start_x, start_y)] # 尝试向上走 if start_x > 0 and maze[start_x-1][start_y] == 0: result = solve_maze(maze, start_x-1, start_y, end_x, end_y, path+[(start_x, start_y)]) if result is not None: return result # 尝试向下走 if start_x < len(maze)-1 and maze[start_x+1][start_y] == 0: result = solve_maze(maze, start_x+1, start_y, end_x, end_y, path+[(start_x, start_y)]) if result is not None: return result # 尝试向左走 if start_y > 0 and maze[start_x][start_y-1] == 0: result = solve_maze(maze, start_x, start_y-1, end_x, end_y, path+[(start_x, start_y)]) if result is not None: return result # 尝试向右走 if start_y < len(maze)-1 and maze[start_x][start_y+1] == 0: result = solve_maze(maze, start_x, start_y+1, end_x, end_y, path+[(start_x, start_y)]) if result is not None: return result # 无路可走,回溯到上一个节点 return None ``` 使用方法如下: ```python maze = [ [0, 1, 0, 0], [0, 0, 0, 1], [1, 0, 1, 0], [0, 0, 0, 0] ] start_x, start_y = 0, 0 end_x, end_y = 3, 3 path = [] result = solve_maze(maze, start_x, start_y, end_x, end_y, path) if result is not None: print("找到一条路径:", result) else: print("没有找到路径。") ``` 输出结果为: ``` 找到一条路径: [(0, 0), (0, 1), (1, 1), (1, 0), (2, 0), (2, 1), (2, 2), (1, 2), (0, 2), (0, 3), (1, 3), (2, 3), (3, 3)] ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值