穿越雷区 | 第六届蓝桥杯国赛C++A组

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

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

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

例如:

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

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

输入格式

第一行是一个整数 n,表示方阵的大小。

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

输出格式

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

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

数据范围

4≤n<1000

输入样例:
5
A + - + -
- + - - +
- + + + -
+ - + - +
B + - + -
输出样例:
10
题解:

        标准的BFS,设置一个新的二维数组num来记录到每个格子的最小路径,通过一个队列来循环,就是标准的BFS的写法。

        但是ACwing的编译器抽风了,我的环境能正常运行但是提交就WA,就只输出2^15。所以就自己写了几个例子,都能过。

代码:
#include<iostream>
#include<cstdio>
#include<cmath>
#include<cstdlib>
#include<cstring>
#include<algorithm>
#include<iomanip>
#include<queue>
#include<stack>
#include<vector>
#include<unordered_set>
#include<unordered_map>
#include<map>
#include<set>
using namespace std;
typedef long long int ll;
const int INF=1e16;

int n;
char m[1001][1001];
int tx[4]={1,0,-1,0};
int ty[4]={0,1,0,-1};
int ans=-1;
int num[1001][1001];

struct node{
    char f;
    int r;
    int x,y;
};

int check(int x,int y,node a){
    if(x>=0 && x<n && y>=0 && y<n && m[x][y]!=a.f && num[x][y]==-1){
        return 1;
    }
    return 0;
}

void bfs(int x,int y){
    node n1;n1.f='-';n1.x=x;n1.y=y;
    node n2;n2.f='+';n2.x=x;n2.y=y;
    queue<node> qu;
    qu.push(n1);qu.push(n2);
    int t=0;
    while(!qu.empty()){
        node a=qu.front();
        //cout << a.x << " " << a.y << "\n";
        qu.pop();
        for(int i=0;i<4;i++){
            int xx=a.x+tx[i];
            int yy=a.y+ty[i];
            if(check(xx,yy,a)){
                node b=a;
                b.r=b.r+1;
                b.x=xx;
                b.y=yy;
                b.f=m[xx][yy];
                num[xx][yy]=b.r;
                qu.push(b);
            }
        }
    }
}

void solve(){
    cin >> n;
    memset(num,-1,sizeof(num));
    int x=0,y=0;
    int bx=0,by=0;
    for(int i=0;i<n;i++){
        for(int j=0;j<n;j++){
            cin >> m[i][j];
            if(m[i][j]=='A'){
                x=i;y=j;
            }
            if(m[i][j]=='B'){
                bx=i;by=j;
            }
        }
    }
    num[x][y]=0;
    bfs(x,y);
    /*
    for(int i=0;i<n;i++){
        for(int j=0;j<n;j++){
            cout << num[i][j] << " ";
        }
        cout << "\n";
    }
    */
    if(num[bx][by]!=-1){
        ans=num[bx][by];
    }
    cout << ans;
}

int main(){
    solve();
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值