穿越雷区--蓝桥杯笔记

题目

X 星的坦克战车很奇怪,它必须交替地穿越正能量辐射区和负能量辐射区才能保持正常运转,否则将报废。

某坦克需要从 A 区到 B 区去( A,B 区本身是安全区,没有正能量或负能量特征),怎样走才能路径最短?

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

例如:

A + - + -

- + - - +

- + + + -

+ - + - +

B + - + -

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

第一行是一个整数 nn,表示方阵的大小, 4 ≤n<100。

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

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

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

题解:

  1. 寻求最少步数,采用bfs;

  1. 于‘A’处入栈,‘B’处return;

  1. 越界和错误条件

代码:

#include<iostream>
#include<cstring>
#include<queue>
#define x first
#define y second
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];
typedef pair<int, int>PII;
int bfs()
{
    queue<PII>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.x + nex[i][0], ty = t.y + nex[i][1];
            if (tx < 0 || ty < 0 || tx >= n || ty >= n || g[tx][ty] == g[t.x][t.y] || dist[tx][ty] != -1)
                continue;
            dist[tx][ty] = dist[t.x][t.y] + 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;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值