蓝桥杯算法-迷宫问题最优解(dfs)

这篇文章介绍了一种使用Java编程实现的迷宫求解算法,通过深度优先搜索(DFS)方法找到从起点S到终点T的最短路径,利用二维数组和布尔数组记录路径状态。
摘要由CSDN通过智能技术生成
输入:
5 6
....S*
.**...
.*..*.
*..**.
.T....
输出:
7

import java.util.*;

public class LANQIAO1 {
    public static int n; // 行
    public static int m; // 列
    public static String[] tmp = new String[110]; // 字符串数组用于给字符数组赋值
    public static char[][] maze = new char[110][110];
    public static boolean[][] vis = new boolean[110][110];
    // 方向数组(x,y 的增量)(逆时针),用于给当前位置加数表示从当前位置,往上 左 下 右 移动
    public static int[][] dir = {{-1,0},{0,-1},{1,0},{0,1}};
    public static boolean f;
    public static int ans = 1000000000;
    // 判断当前位置是否合法(在迷宫数组中没有越界)
    public static boolean in(int x, int y) {
        return x >= 0 && x < n && y >= 0 && y < m;
    }
    // 返回能不能走出去
    public static void dfs(int x ,int y, int step){
        if(maze[x][y] == 'T'){
            if(step < ans){
                ans = step;
            }
            return;
        }
        vis[x][y] = true;
        for (int i = 0; i < 4; i++) {
            int tx = x + dir[i][0];
            int ty = y + dir[i][1];
            if(in(tx,ty) && maze[tx][ty] != '*' && !vis[tx][ty]){
                dfs(tx,ty,step + 1);
            }
        }
        // 取消标记,因为以后还要搜
        vis[x][y] = false;

    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        n = sc.nextInt();
        m = sc.nextInt();
        for (int i = 0; i < n; i++) {
            tmp[i] = sc.next();
        } // 串数组给字符数组赋值
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                maze[i][j] = tmp[i].charAt(j);
            }
        }
        // 先找出起始点,才能知道从哪开始搜
        int x = 0, y = 0;
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                if (maze[i][j] == 'S') {
                    x = i;
                    y = j;
                }
            }
        }
        // 找到终点,打出地图

        dfs(x, y, 0);
        System.out.println(ans);
    }
}
  • 14
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值