您的位置:首页 > 其它

HDOJ1242(延时迷宫BFS)

2015-08-28 20:05 281 查看
代码一:

#include<iostream>
#include<cstdio>
#include<queue>
using namespace std;
const int MAX_N=205;
const int INF=0x30303030;
char map[MAX_N][MAX_N];
int N,M;
int sx,sy;
int gx,gy;
int dx[4]={1, 0, -1, 0};
int dy[4]={0, 1, 0, -1};
typedef pair<int, int> P;
int dist[MAX_N][MAX_N];
int bfs(int y, int x)
{
for(int i=0; i<N; i++)
for(int j=0; j<M; j++)
dist[i][j]=INF;
dist[sy][sx]=0;
queue<P> que;
que.push(P(sy,sx));

while(!que.empty())
{
P pos=que.front();que.pop();
int y=pos.first;
int x=pos.second;
if(y==gy&&x==gx)
{
break;
}
for(int i=0; i<4; i++)
{
int ny=y+dy[i];
int nx=x+dx[i];
if(0<=ny&&ny<N&&0<=nx&&nx<M&&map[ny][nx]!='#')
{
int d;
if(map[ny][nx]=='x')
{
d=dist[y][x]+2;
}
else
{
d=dist[y][x]+1;
}
if(d>=dist[ny][nx])
{
continue;
}
dist[ny][nx]=d;
que.push(P(ny,nx));
}
}

}
return dist[gy][gx];
}

int main()
{
while(cin>>N>>M)
{
for(int i=0; i<N; i++)
{
for(int j=0; j<M; j++)
{
cin>>map[i][j];
if(map[i][j]=='r')
{
sy=i;
sx=j;
}
if(map[i][j]=='a')
{
gy=i;
gx=j;
}
}
}

int exist=bfs(sy,sx);
if(exist==INF)
{
cout<<"Poor ANGEL has to stay in the prison all his life."<<endl;
}
else
{
cout<<exist<<endl;
}
}
return 0;
}


代码二:

#include"iostream"
#include"queue"
using namespace std;
const int INF=0x30303030;
const int MAX_N=205;
int N, M;
char map[MAX_N][MAX_N];
int sy, sx;
int gx, gy;
int dx[4]={1, 0, -1, 0};
int dy[4]={0, 1, 0, -1};
int d[MAX_N][MAX_N];
struct node{
int y;
int x;
int step;
node(int y, int x, int step)
{
this->y=y;
this->x=x;
this->step=step;
}
friend bool operator<(node no1, node no2)
{
return no1.step > no2.step;
}
};

void dfs()
{
for(int i=0; i<N; i++)
{
for(int j=0; j<M; j++)
{
d[i][j]=INF;
}
}

int ans;
bool exist=false;
priority_queue<node> que;
que.push(node(sy,sx,0));
while(!que.empty())
{
node now=que.top();que.pop();
if(now.y==gy&&now.x==gx)
{
ans=now.step;
exist=true;
break;
}
for(int i=0; i<4; i++)
{
int ny=now.y+dy[i];
int nx=now.x+dx[i];
if(0<=ny&&ny<N&&0<=nx&&nx<M&&map[ny][nx]!='#')
{
int dist;
if(map[ny][nx]=='x')
{
dist=now.step+2;
}
else
{
dist=now.step+1;
}
if(dist>=d[ny][nx])    continue;
d[ny][nx]=dist;
que.push(node(ny,nx,dist));
}
}
}

if(exist)
{
cout<<ans<<endl;
}
else
{
cout<<"Poor ANGEL has to stay in the prison all his life."<<endl;
}
}

int main()
{
while(cin>>N>>M)
{
for(int i=0; i<N; i++)
{
for(int j=0; j<M; j++)
{
cin>>map[i][j];
if(map[i][j]=='r')
{
sy=i;
sx=j;
}
if(map[i][j]=='a')
{
gy=i;
gx=j;
}
}
}
dfs();
}

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: