【无标题】

该问题描述了一个在正负能量辐射区中寻找最短路径的问题,使用了广度优先搜索(BFS)算法来解决。坦克必须在正负区域间交替移动,从A点到达B点。给定一个标记了正负能量的网格地图,代码实现通过BFS找到从A到B的最短步数。
摘要由CSDN通过智能技术生成

穿越雷区

X 星的坦克战车很奇怪,它必须交替地穿越正能量辐射区和负能量辐射区才能保持正常运转,否则将报废。
某坦克需要从 A 区到 B 区去( A,B 区本身是安全区,没有正能量或负能量特征),怎样走才能路径最短?
已知的地图是一个方阵,上面用字母标出了 A,B 区,其它区都标了正号或负号分别表示正负能量辐射区。
例如:

A + - + -

- + - - +

- + + + -

+ - + - +

B + - + -
坦克车只能水平或垂直方向上移动到相邻的区。
示例
输入

5
A + - + -
- + - - +
- + + + -
+ - + - +
B + - + -

输出

10

直接上bfs代码:

#include <bits/stdc++.h>
using namespace std;
int nex[4][2] = { {0,1},{1,0},{-1,0},{0,-1} };
const int N = 1e2 + 10;   int n;  char g[N][N]; int dist[N][N];
int bfs()
{
    queue<pair<int,int>> q;
    memset(dist, -1, sizeof dist);
    for (int i = 0; i < n; i++)
        for(int j=0;j<n;j++)
            if (g[i][j] == 'A'){
                dist[i][j] = 0;
                q.push({ i,j });
            }
    while (q.size()){
        auto t = q.front();
        q.pop();
        for (int i = 0; i < 4; i++){
            int tx = t.first + nex[i][0], ty = t.second + nex[i][1];
            if (tx < 0 || ty < 0 || tx >= n || ty >= n || g[tx][ty] == g[t.first][t.second] || dist[tx][ty] != -1)
                continue;
            dist[tx][ty] = dist[t.first][t.second] + 1;
            if (g[tx][ty] == 'B')
                return dist[tx][ty];
            q.push({ tx,ty });
        }
    }
    return -1;
}
int main()
{
    cin >> n;
    for (int i = 0; i < n; i++)
        for (int j = 0; j < n; ++j)
            cin >> g[i][j];
    cout << bfs() << endl;
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值