蓝桥杯算法dfs迷宫问题优化

将四个方向归纳为一个数组,换方向代码少写了3/4
输入;
5 6
....S*
.***..
.*..*.
*.***.
.T....
输出:
....m*
.***mm
.*..*m
*.***m
.Tmmmm

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 in(int x, int y) {
        return x >= 0 && x < n && y >= 0 && y < m;
    }
    // 返回能不能走出去
    public static boolean dfs(int x, int y){
        if(maze[x][y] == 'T') {
            return true;
        }
        vis[x][y] = true;
        maze[x][y] = 'm';

        for (int i = 0; i < 4; i++) {
            int tx ,ty ;
            tx = x + dir[i][0];
            ty = y + dir[i][1];
            if(in(tx,ty) && maze[tx][ty] != '*' && !vis[tx][ty]){
                if(dfs(tx,ty)){
                    return true;
                }
            }
        }
        // 如果找不到终点则取消标记
        vis[x][y] = false;
        maze[x][y] = '.';
        // 该点不行,返回上一级尝试下一个方向
        return 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;
                }
            }
        }
        // 找到终点,打出地图
        if(dfs(x,y)){
            for (int i = 0; i < n; i++) {
                for (int j = 0; j < m; j++) {
                    System.out.print(maze[i][j]);
                }
                System.out.println();
            }
        }else {
            System.out.println("NO");
        }
    }
}
  • 9
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值