问题 1825: [蓝桥杯][2015年第六届真题]穿越雷区
时间限制: 1Sec 内存限制: 128MB 提交: 310 解决: 211
题目描述
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 + - + -
样例输出
扫描二维码关注公众号,回复:
8915977 查看本文章
10
#include <iostream>
#include <queue>
using namespace std;
struct node{
int x;
int y;
int step;
int status; //+为1,负为-1,正常为0
node(int x, int y, int step = 0, int status = 0): x(x), y(y), step(step), status(status) {}
};
char mp[105][105];
bool vis[105][105]; //记录该点是否已经访问过
int n, sx, sy;
const int dir[4][2] = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}};//方向数组
bool in(int x, int y){ //判断当前坐标是否超界
return x >= 0 && x < n && y >= 0 && y < n;
}
int bfs(node n){
queue<node>q;
q.push(n);
while(!q.empty()){
node now = q.front();
q.pop();
if(mp[now.x][now.y] == 'B'){
return now.step;
}
for(int i = 0; i < 4; i++){ //以当前点为基准,以四个方向进行试探
node next = now;
next.x += dir[i][0];
next.y += dir[i][1];
if(!vis[next.x][next.y] && in(next.x, next.y)){
if((mp[next.x][next.y] == '+' && next.status != 1) || (mp[next.x][next.y] == '-' && next.status != -1) || mp[next.x][next.y] == 'B'){//根据题目要求进行判断
vis[next.x][next.y] = true;//标记该点已经访问过
next.step++; //步数记得+1
if(mp[next.x][next.y] == '+'){//修改状态
next.status = 1;
}
if(mp[next.x][next.y] == '-'){//修改状态
next.status = -1;
}
q.push(next); //入队列
}
}
}
}
return -1;
}
int main(){
cin >> n;
for(int i = 0; i < n; i++){
for(int j = 0; j < n; j++){
cin >> mp[i][j];
if(mp[i][j] == 'A'){
sx = i;
sy = j;
}
}
}
node n(sx, sy);
vis[sx][sy] = true;
cout << bfs(n) << endl;
return 0;
}