【思特奇杯·云上蓝桥-算法集训营】第2周 04-穿越雷区

04-穿越雷区

题目描述

已知的地图是一个方阵,上面用字母标出了A,B区,其它区都标了正号或负号分别表示正负能量辐射区。

例如:

A + - + -

- + - - +

- + + + -

+ - + - +

B + - + -

坦克车只能水平或垂直方向上移动到相邻的区。

数据格式要求:

输入第一行是一个整数n,表示方阵的大小, 4<=n<100

接下来是n行,每行有n个数据,可能是A,B,+,-中的某一个,中间用空格分开。

A,B都只出现一次。

要求输出一个整数,表示坦克从A区到B区的最少移动步数。

如果没有方案,则输出-1

例如:

用户输入:

5

A + - + -

- + - - +

- + + + -

+ - + - +

B + - + -

则程序应该输出:

10

资源约定:

峰值内存消耗 < 512M

CPU消耗 < 1000ms

请严格按要求输出,不要画蛇添足地打印类似:“请您输入…” 的多余内容。

所有代码放在同一个源文件中,调试通过后,拷贝提交该源码。

注意: main函数需要返回0

注意: 只使用ANSI C/ANSI C++ 标准,不要调用依赖于编译环境或操作系统的特殊函数。

注意: 所有依赖的函数必须明确地在源文件中 #include , 不能通过工程


dfs题目,注意回溯时的细节

import java.util.Scanner;

public class code04_crossMines {
    static int res = Integer.MAX_VALUE;

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

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        char[][] mines = new char[n][n];
        int row = 0, col = 0;
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                mines[i][j] = sc.next().charAt(0);
                if (mines[i][j]=='A') {
                    row = i;
                    col = j;
                }
            }
        }
       //记录是否被访问过
        int[][] visited = new int[n][n];
        countStep(mines, visited, row, col, 0);
        System.out.println(res);
        sc.close();

    }

    public static void countStep(char[][] mines, int[][] visited, int row, int col, int step) {
        //到达B区 认为有一条路径 取最小值
        if (mines[row][col]=='B') {
            if (step < res) {
                res = step;
            }
            return;
        }
        visited[row][col] = 1;
        for (int i = 0; i < dir.length; i++) {
            int nextRow = row + dir[i][0];
            int nextCol = col + dir[i][1];
            //判断是否越界
            if (nextCol < 0 || nextRow < 0 || nextRow >= mines.length || nextCol >= mines.length) {
                continue;
            }
            if (visited[nextRow][nextCol] == 0) {
                visited[nextRow][nextCol] = 1;
                //每次走的 能量区不能一样
                if (mines[nextRow][nextCol]!=mines[row][col]) {
                    countStep(mines, visited, nextRow, nextCol, step + 1);
                }
                //回溯 
                visited[nextRow][nextCol] = 0;
            }

        }
    }

}

运行结果
在这里插入图片描述

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值