蓝桥杯 穿越雷区

穿越雷区

问题描述

X星的坦克战车很奇怪,它必须交替地穿越正能量辐射区和负能量辐射区才能保持正常运转,否则将报废。
某坦克需要从A区到B区去(A,B区本身是安全区,没有正能量或负能量特征),怎样走才能路径最短?

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

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

数据格式要求:

输入第一行是一个整数n,表示方阵的大小, 4<=n<100
接下来是n行,每行有n个数据,可能是A,B,+,-中的某一个,中间用空格分开。
A,B都只出现一次。

要求输出一个整数,表示坦克从A区到B区的最少移动步数。
如果没有方案,则输出-1

例如:
用户输入:
5
A + - + -
- + - - +
- + + + -
+ - + - +
B + - + -

则程序应该输出:
10

思路

  • 因为是找最短路径,所以使用广搜比深搜快
  • 使用一个数组记录是否访问过

代码

n = int(input())

m = [input().split(' ') for _ in range(n)]

visit = [[False] * n for _ in range(n)] # 记录是否访问过

step = [(0, -1), (0, 1), (-1, 0), (1, 0)]

queue = [(0, 0, 0)] # 存三个值:坐标、当前移动的步数

while queue:
    y, x, t = queue.pop(0)
    if m[y][x] == 'B':
        print(t)
        break
    for dy, dx in step:
        ny = y + dy
        nx = x + dx
        if -1 < nx < n and -1 < ny < n:
            if not visit[ny][nx] and m[y][x] != m[ny][nx]:
            	# 没有访问过并且不是连续走相同的区域
                queue.append((ny, nx, t+1))
                visit[y][x] = True
    
if not queue:
    print(-1)
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,以下是一个简单的 Java 代码示例,用于生成一个包含随机雷的二维雷区,每个格子用数字表示周围雷的数量: ```java import java.util.Random; public class MineSweeper { private int[][] board; private int row; private int col; private int numMines; public MineSweeper(int row, int col, int numMines) { this.row = row; this.col = col; this.numMines = numMines; this.board = new int[row][col]; generateMines(); countMines(); } private void generateMines() { Random rand = new Random(); int mines = numMines; while (mines > 0) { int r = rand.nextInt(row); int c = rand.nextInt(col); if (board[r][c] != -1) { board[r][c] = -1; mines--; } } } private void countMines() { for (int r = 0; r < row; r++) { for (int c = 0; c < col; c++) { if (board[r][c] == -1) { continue; } int count = 0; if (r > 0 && c > 0 && board[r-1][c-1] == -1) { count++; } if (r > 0 && board[r-1][c] == -1) { count++; } if (r > 0 && c < col-1 && board[r-1][c+1] == -1) { count++; } if (c > 0 && board[r][c-1] == -1) { count++; } if (c < col-1 && board[r][c+1] == -1) { count++; } if (r < row-1 && c > 0 && board[r+1][c-1] == -1) { count++; } if (r < row-1 && board[r+1][c] == -1) { count++; } if (r < row-1 && c < col-1 && board[r+1][c+1] == -1) { count++; } board[r][c] = count; } } } public void printBoard() { for (int r = 0; r < row; r++) { for (int c = 0; c < col; c++) { if (board[r][c] == -1) { System.out.print("* "); } else { System.out.print(board[r][c] + " "); } } System.out.println(); } } public static void main(String[] args) { MineSweeper game = new MineSweeper(5, 5, 5); game.printBoard(); } } ``` 示例输出: ``` 0 1 1 * 2 2 * 3 3 * * 4 * 4 3 2 * 3 * 2 1 1 2 1 0 ``` 其中,-1 表示一个雷,其余数字表示周围雷的数量。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值