标题:穿越雷区
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
资源约定:
峰值内存消耗(含虚拟机) < 512M
CPU消耗 < 2000ms
请严格按要求输出,不要画蛇添足地打印类似:“请您输入...” 的多余内容。
基础的广搜
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <queue>
using namespace std;
int n; //地图大小
char ch[99][99]; //地图数组
//方向数组
int dx[4] = {0,1,-1,0};
int dy[4] = {1,0,0,-1};
int vis[110][110]; //标记数组,防止一个点走两遍
struct xy{
int x;
int y;
int step;
};
void bfs(int i,int j){
xy start,temp; //定义两个结构体变量,用于标记起始位置和队首位置
start.x = i;
start.y = j;
start.step = 0;
queue<xy> q;
q.push(start);
while(!q.empty()){
temp = q.front(); //取出队首元素
q.pop();
if(ch[temp.x][temp.y]=='B'){
cout<<temp.step<<endl;
return ;
}
xy next;
for(int i=0;i<4;i++){
int nx = temp.x + dx[i];
int ny = temp.y + dy[i];
if(nx<n && nx>=0 && ny<n && ny>=0 && !vis[nx][ny] && ch[temp.x][temp.y]!=ch[nx][ny]){
next.x = nx;
next.y = ny;
next.step = temp.step + 1;
vis[nx][ny] = 1;
q.push(next);
}
}
}
}
int main()
{
cin>>n;
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
cin>>ch[i][j];
}
}
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
if(ch[i][j]=='A'){
bfs(i,j);
}
}
}
return 0;
}
提供一组数据
20
A + - + + + + + - + - + + + + - + + - +
- - + - + - - + + - - + - - - - + - - -
- + - + + + - + - + - - + + + - + + - -
- - + - - - - - + + + - + - + + + - - +
- - - - + + - + + - + - - + + + - - - -
- + - + + - + - + - - + + + - + + - + +
- + - + - - + + + + + + - + + - - - - -
- + + + + + - - + - - - - + - + - - + -
- + + - + + + + - + + + + - + - + - - -
+ - + + - - + - - - - - - + + - - - + -
+ - - + - + - + + - - + + + - + - - + -
- + - + - + - + - + + - + - + - + + - -
+ + - - - - - + - - - - + - + + + + + -
+ + - + - + + + + - + + + - + - + - + -
- + - - + - - - + + + - - - + + - + - +
- + - - - - + - - + - + + - - - + - - +
+ - + - + + + + - - + - + - - - + - + +
+ - - - - - + - - - - + - - - + - + - +
+ + - + - + + + - - + + + + + - - - - -
B - - - + - + - - + + - - + + + + - + +
输出45