HDU-2612-Find a way
2838 ワード
//この問題は一晩中私をだまして、C++で交際するのはだめで、結局CあるいはG++で来て、おや...この問題はBFSを使えば,"@"点に到達したステップ数を保存し,bfsは送らないまで探索し続けたことを理解させる.後はメイン関数で出力比較を行います...
ACコード:
ACコード:
#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
#define N 205
char map[N][N];
int vis[N][N];
int dp1[N][N],dp2[N][N];
int x1,y1,x2,y2;
struct node
{
int x,y,step;
}queue[N*N];
int dir[4][2]={{1,0},{0,1},{-1,0},{0,-1}};
int n,m;
void bfs1()
{
struct node now,pre;
queue[0].x=x1;
queue[0].y=y1;
queue[0].step=0;
int e=0,h=1;
while(e<h)
{
pre=queue[e];
for(int i=0;i<4;i++)
{
now.x=pre.x+dir[i][0];
now.y=pre.y+dir[i][1];
now.step=pre.step+1;
if(now.x>=0&&now.x<n&&now.y>=0&&now.y<m&&!vis[now.x][now.y]&&map[now.x][now.y]!='#')
{
dp1[now.x][now.y]=now.step;
vis[now.x][now.y]=1;
queue[h++]=now;
}
}
e++;
}
return;
}
void bfs2()
{
struct node now,pre;
queue[0].x=x2;
queue[0].y=y2;
queue[0].step=0;
int e=0,h=1;
while(e<h)
{
pre=queue[e];
for(int i=0;i<4;i++)
{
now.x=pre.x+dir[i][0];
now.y=pre.y+dir[i][1];
now.step=pre.step+1;
if(now.x>=0&&now.x<n&&now.y>=0&&now.y<m&&!vis[now.x][now.y]&&map[now.x][now.y]!='#')
{
dp2[now.x][now.y]=now.step;
vis[now.x][now.y]=1;
queue[h++]=now;
}
}
e++;
}
return;
}
int main()
{
while(scanf("%d%d",&n,&m)!=EOF)
{
memset(dp1,0,sizeof(dp1));
memset(dp2,0,sizeof(dp2));
int i,j;
for(i=0;i<n;i++)
{
scanf("%s",map[i]);
}
for(i=0;i<n;i++)
{
for(j=0;j<m;j++)
{
if(map[i][j]=='M')
{
x1=i;
y1=j;
}
if(map[i][j]=='Y')
{
x2=i;
y2=j;
}
}
}
memset(vis,0,sizeof(vis));
bfs1();
memset(vis,0,sizeof(vis));
bfs2();
int MIN=N*N;
for(i=0;i<n;i++)
{
for(j=0;j<m;j++)
{
if(map[i][j]=='@'&&dp1[i][j]&&dp2[i][j])
{
MIN=min(MIN,dp1[i][j]+dp2[i][j]);
}
}
}
printf("%d
",MIN*11);
}
return 0;
}