题目描述
交替地穿越正能量辐射区和负能量辐射区,需要从A区到B区去(A,B区本身是安全区,没有正能量或负能量特征),怎样走才能路径最短?
例如:
A + - + -
- + - - +
- + + + -
+ - + - +
B + - + -
只能水平或垂直方向上移动到相邻的区。
输入
输入第一行是一个整数n,表示方阵的大小, 4<=n<100
接下来是n行,每行有n个数据,可能是A,B,+,-中的某一个,中间用空格分开。
A,B都只出现一次。
输出
要求输出一个整数,表示坦克从A区到B区的最少移动步数。
如果没有方案,则输出-1
样例输入
5
A + - + -
- + + + -
+ - + - +
B + - + -
样例输出
10
思路
求最小步数,用BFS,入队的元素设置为结点,每次入队时判断与上次的符号是否一样,若不同,可以入队,结点步数加一。直到出队的元素就是’B’,此节点的步骤数就是答案,结束。若队列为空还没到达’B’,说明到达不了,输出-1。
注意:输入字符时,若用scanf("%c"),要用getchar()接受空格或换行;但是可直接使用cin>>,就不需要额外处理了。
代码
#include<bits/stdc++.h>
using namespace std;
const int maxn=102;
int n,sx,sy,ex,ey;
char Map[maxn][maxn];
bool vis[maxn][maxn];
int X[]={-1,1,0,0};
int Y[]={0,0,-1,1};
struct node{
int x,y,step;//坐标与步数
}t1,t2;
int bfs(){
queue<node> Q;
t1.x=sx;
t1.y=sy;
t1.step=0;
Q.push(t1);
vis[t1.x][t1.y]=true;
while(!Q.empty()){
t1=Q.front();
Q.pop();
if(t1.x==ex&&t1.y==ey){
return t1.step;
}
for(int i=0;i<4;i++){
int newX=t1.x+X[i];
int newY=t1.y+Y[i];
if(newX>=0 && newX<n && newY>=0 && newY<n && !vis[newX][newY]){
if(Map[t1.x][t1.y]!=Map[newX][newY]){//交替穿过字符
t2.x=newX;
t2.y=newY;
t2.step=t1.step+1;
Q.push(t2);
}
}
}
}
return -1;
}
int main(){
scanf("%d",&n);
getchar();
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
// cin>>Map[i][j];
scanf("%c",&Map[i][j]);
getchar();
if(Map[i][j]=='A'){//记录起始坐标
sx=i;
sy=j;
}else if(Map[i][j]=='B'){
ex=i;
ey=j;
}
}
}
int ans=bfs();
printf("%d",ans);
return 0;
}