2021度小满9.20编程笔试

第一题涂色很简单,就是个简单的模拟
说说第二题吧,经典走迷宫问题,就是遇到*步数加一,遇到.直接前进,遇到#无法前进,只要走到四个边缘之一就算走出迷宫,问最小步数。
这题暴力dfs会超时,也就过个9%…
利用记忆化搜索加剪枝即可,贴个代码吧

import java.util.*;

public class Main {
    static Scanner in = new Scanner(System.in);
    static int n,m,ans ;
    static char[][] mp;
    static int[][] dp;
    static int[][] bool;
    static int[][] dir = {{0,1},{1,0},{0,-1},{-1,0}};
    public static void dfs(int x, int y, int sp) {
        if(x < 0 || x >= n || y < 0 || y >= m) {
            ans = Math.min(sp, ans);
            return;
        }
        if(bool[x][y]==1) return;
        if(sp >= dp[x][y]) {//key code 步数更大的直接返回
            return;
        } else {
            dp[x][y] = sp;//步数更小的则直接更新
        }
        bool[x][y] = 1;
        if(mp[x][y] == '#') return;
        if(mp[x][y] == '*') sp++;
        int tx,ty;
        for(int i = 0; i < 4; i++) {
            tx = x+dir[i][0];
            ty = y+dir[i][1];
            dfs(tx,ty, sp);
        }
        bool[x][y] = 0;
    }
    public static void main(String[] args) {
        int t = in.nextInt();
        while(t-->0){
             ans = Integer.MAX_VALUE;
             n = in.nextInt();
             m = in.nextInt();
             mp = new char[n][m];
             dp = new int[n][m];
             bool = new int[n][m];
            int x = 0,y =0 ;
            for (int i = 0; i < n; i++) {
                mp[i] = in.next().toCharArray();
                for (int j = 0; j < m; j++) {
                    if(mp[i][j] == '@'){
                        x = i;
                        y = j;
                    }
                    dp[i][j] = Integer.MAX_VALUE;
                    bool[i][j] = 0;

                }
            }
            dfs(x,y,0);
            if(ans == Integer.MAX_VALUE)
                System.out.println(-1);
            else
                System.out.println(ans);


        }
    }
}

简单测试用例:

3
3 4
####
#@.*
**.*
0
3
3
###
#@#
.#.
-1
3 3
###
#@*
.**
1
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值