问题 1825: [蓝桥杯][2015年第六届真题]穿越雷区
时间限制: 1Sec 内存限制: 128MB 提交: 339 解决: 231
题目描述
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
思路:
再进行搜索的时候,我们记录前一步的状态,在走此步的时候,我们判断一下上一步的状态就可以了。
代码:
#include<iostream>
#include<algorithm>
#define rep(i,a,b) for(int i=a;i<=b;i++)
#define dep(i,a,b) for(int i=a;i>=b;i--)
#define ll long long
#include<string.h>
#include<queue>
#include<stack>
#include<cstdio>
using namespace std;
const int maxn=100+6;
#define mod 1000000007
#define INF 0x3f3f3f3f
int dx[]={-1,1,0,0};
int dy[]={0,0,-1,1};
char ch[maxn][maxn];
int n;
int bx,by,ex,ey;
struct node
{
int x;
int y;
int step;
char before;
};
bool vis[maxn][maxn];
bool check(int x,int y,char c)
{
if(!vis[x][y]&&x>0&&y>0&&x<=n&&y<=n&&ch[x][y]!=c)
{
return 1;
}
return 0;
}
int bfs()
{
queue<node>q;
while(q.size())q.pop();
q.push(node{bx,by,0,'r'});
vis[bx][by]=1;
while(q.size())
{
node now,nxt;
now=q.front();
q.pop();
if(now.x==ex&&now.y==ey)
{
return now.step;
}
for(int i=0;i<4;i++)
{
int x=now.x+dx[i];
int y=now.y+dy[i];
if(check(x,y,now.before))
{
q.push(node{x,y,now.step+1,ch[x][y]});
vis[x][y]=1;
}
}
}
return -1;
}
int main()
{
cin>>n;
rep(i,1,n)
{
rep(j,1,n)
{
cin>>ch[i][j];
if(ch[i][j]=='A')
{
bx=i;
by=j;
}
if(ch[i][j]=='B')
{
ex=i;
ey=j;
}
}
}
int ans=bfs();
cout<<ans<<endl;
}