/*
2014-5-8
21:34
DFS
poj 3008
*/
#include <cstdio>
#include <string.h>
#define MAXN 30
using namespace std;
//input
int w,h; //wight hight
int graph[MAXN][MAXN];
int sx,sy,ex,ey;
int dx[4] = {0,0,-1,1},dy[4] = {-1,1,0,0};
int ans,cnt;
void dfs(int x,int y,int cnt){
int nx,ny,i;
if(cnt > ans)
return ;
for(i = 0;i < 4; i++){
nx = x+dx[i];
ny = y+dy[i];
if(nx>=h || nx<0 || ny>=w || ny<0 || graph[nx][ny]==1)//越界或立即有阻挡物剪枝
continue;
while(nx <= h && nx>=0 && ny>=0 && ny<=w && graph[nx][ny]!=1){
if(nx == ex&&ny == ey){
if(cnt+1 < ans)
ans = cnt+1;
break;
}
nx += dx[i];
ny += dy[i];
}
if(nx==ex && ny==ey)//若由于到终点跳出去
continue;
if(nx<h && nx>=0 && ny < w && ny>=0)
{
graph[nx][ny]=0;//若是碰到阻挡物。阻挡物消失。
dfs(nx-dx[i],ny-dy[i],cnt+1);//继续搜索
graph[nx][ny]=1;//还原阻挡物。回溯
}
}
}
int main()
{
while(scanf("%d%d",&w,&h) && w && h){
ans = 12;
for(int i = 0;i < h;i++){
for(int j = 0;j < w; j++){
scanf("%d",&graph[i][j]);
if(graph[i][j] == 2){
sx = i,sy = j;
}
if(graph[i][j] == 3)
ex=i,ey=j;
}
}
dfs(sx,sy,0);
if(ans <= 10)
printf("%d\n",ans);
else
printf("-1\n");
}
return 0;
}
poj 3009Curling 2.0
最新推荐文章于 2022-10-03 16:25:58 发布