穿越雷区(Java)

  1. 见过很多次了,向不同方向搜索。
  2. code:
import java.util.Scanner;

public class Main {

    private static int step = 10000000;

    private static int dir[][] = new int[][] {{-1,0},{0,1},{1,0},{0,-1}};

    private static char[][] c = new char[101][101];

    private static boolean[][] vis = new boolean[101][101];

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        while(sc.hasNext()) {
            int n = Integer.parseInt(sc.nextLine());
            int sx = 0, sy = 0, ex = 0, ey = 0;
            for(int i = 0;i<n;i++) {
                String s = sc.nextLine();
                for(int j = 0;j<n;j++) {
                    c[i][j] = s.charAt(j*2);
                    if(c[i][j] == 'A') {
                        sx = i;
                        sy = j;
                    }
                    if(c[i][j] == 'B') {
                        ex = i;
                        ey = j;
                    }
                }
            }

            vis[sx][sy] = true;
            dfs(sx, sy, 0, n, ex, ey, 'A');
            if(step == 10000000)
                System.out.println(-1);
            else
                System.out.println(step);
        }
        sc.close();
    }

    public static void dfs(int x, int y, int t, int n, int ex, int ey, char ch) {
        if(x<0 || x>n || y<0 || y>n)  
            return;  
        if(x==ex && y==ey) {  
            if(t<step)  
                step=t;  
            return;  
        }

        for(int k = 0;k<4;k++) { //向四个方向搜索
            int px = x + dir[k][0], py = y + dir[k][1];
            if(px > n || px < 0 || py > n || py < 0)
                continue;
            if(!vis[px][py] && c[px][py]!=ch) {  
                vis[px][py] = true;  
                dfs(px,py,t+1,n, ex, ey, c[px][py]);  
                vis[px][py] = false;  
            }
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值