您的位置:首页 > 其它

poj 3009(深度搜索)

2012-11-03 15:09 246 查看
#include<stdio.h>
#include<string.h>
#include<iostream>
using namespace std;

#define N 22
int map

;
int minstep;

int dir[4][2]={{-1,0},{1,0},{0,-1},{0,1}};
int w,h;

bool check(int x,int y)
{
if(x>=1 && x<=h && y>=1 && y<=w)
return 1;
return 0;
}
void dfs(int step ,int x, int y)
{

if(step>= 10)
return ;
for(int i=0;i<4;i++)
{
int xx=x+dir[i][0];
int yy=y+dir[i][1];

if(map[xx][yy]== 1)
continue;

while(map[xx][yy]==0)
{
xx=xx+dir[i][0];
yy=yy+dir[i][1];
}

if(check(xx,yy))
{
if(map[xx][yy]==1)
{
map[xx][yy]=0;
dfs(step+1,xx-dir[i][0],yy-dir[i][1]);
map[xx][yy]=1;
}
if(map[xx][yy]==3)
{
if(step+1<minstep)
minstep=step+1;
}
}
}
}

int main()
{
int i,j;
int dx,dy;
while(scanf("%d%d",&w,&h)!=EOF)
{
if(w==0 && h==0)
break;
//memset( map,0,sizeof(map) );
for(i=1;i<=h;i++)
for(j=1;j<=w;j++)
{
cin>>map[i][j];
if(map[i][j] == 2)
{
dx=i;
dy=j;
map[i][j]=0;
}
}
minstep=9999999;
dfs(0,dx,dy);
// dfs(0,dx,dy);
if(minstep<=10)
printf("%d\n",minstep);
else
printf("-1\n");
}

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