您的位置:首页 > 其它

POJ 2312 - Battle City

2012-10-25 13:18 197 查看
题目就是根据我们小时候经常玩的游戏坦克大战,

图上有你自己的位置Y,硬墙S,砖块B,河R,空地E,目标位置T,硬墙和河都是不能通过的,通过空地需要1步,而通过砖块则需要两步,给出一个图,要求共需要要多少步能从当前位置到达目标位置;
思路分析:BFS,由于砖块需要两步,所以每次需要比较到达某一位置的步数,记忆化搜索,其他的和一般简单的BFS没什么区别;
code:
#include<iostream>
#include<cstdio>
#include<queue>
#include<memory.h>
using namespace std;
struct node
{
int x,y,step;
} p,q;
int direct[4][2]= {{1,0},{-1,0},{0,1},{0,-1}};
int num[301][301];
char map[301][301];
int m,n,x,y,xx,yy;
int judge(int x1,int y1)
{
return (x1>=0 && x1<m && y1>=0 && y1<n && map[x1][y1]!=\'S\' && map[x1][y1]!=\'R\');
}
void bfs()
{
queue<node> Q;
q.x=x;
q.y=y;
q.step=0;
Q.push(q);
while(!Q.empty())
{
q=Q.front();
Q.pop();
for(int i=0; i<4; i++)
{
p.x=q.x+direct[i][0];
p.y=q.y+direct[i][1];
if(judge(p.x,p.y))
{
if(map[p.x][p.y]==\'B\')
p.step=q.step+2;
else
p.step=q.step+1;
if(num[p.x][p.y]>p.step)
{
num[p.x][p.y]=p.step;
Q.push(p);
}
}
}
}
}
int main()
{
//freopen(\"in.txt\",\"r\",stdin);
while(cin>>m>>n && (m||n))
{
memset(map,\'S\',sizeof(map));
for(int i=0;i<m;i++)
for(int j=0;j<n;j++)
num[i][j]=10000000;
for(int i=0; i<m; i++)
{
getchar();
for(int j=0; j<n; j++)
{
char c=getchar();
if(c==\'Y\')
{
x=i;
y=j;
}
if(c==\'T\')
{
xx=i;
yy=j;
}
map[i][j]=c;
}
}
bfs();
if(num[xx][yy]!=10000000)
cout<<num[xx][yy]<<endl;
else
cout<<\"-1\"<<endl;
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: