您的位置:首页 > 其它

HDOJ 1026 dfs路径保存

2013-12-27 15:59 239 查看
#include<cstdio>
#include<cstring>
#include<cmath>
int g[101][101];
#define inf 0xffffff
int n,m;
int min;
int sx[4]={0,1,0,-1};
int sy[4]={1,0,-1,0};
int que[1001][2];
int front,rear;
void dfs(int x,int y,int c_step)
{
if(x==n&&y==m)
{
if(c_step<min)
{min=c_step;return;}
}
if(abs(x-n)+abs(y-m)+c_step>n*m-1)return;
for(int i=0;i<4;i++)
{
int xx,yy;
xx=x+sx[i];
yy=y+sy[i];
if(xx<=n&&xx>=1&&yy<=m&&yy>=1&&g[xx][yy]!=-1)
{
int zhi=g[xx][yy];
g[xx][yy]=-1;
dfs(xx,yy,c_step+zhi+1);
g[xx][yy]=zhi;
}

}

}
int main()
{
char c;
int i,j;
while(scanf("%d %d",&n,&m)!=EOF)
{
getchar();
for(i=1;i<=n;i++)
{
for(j=1;j<=m;j++)
{
c=getchar();
if(c=='.')
g[i][j]=0;
else if(c=='#')
g[i][j]=-1;
else
g[i][j]=c-'0';
}
getchar();
}
min=inf;
int start=g[1][1];
dfs(1,1,start);
printf("\n");
if(min>n*m-1)
printf("God please help our poor hero.\n");
else
printf("It takes %d seconds to reach the target position, let me show you the way.\n",min);
printf("FINISH\n");
}
return 0;
}


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