poj 3009 Curling 2.0

#include <iostream>            //dfs
#include <deque>
using namespace std;
int w,h,square[100][100],c,num;
void dfs(int x,int y)
{
if(c>num)
return;
int i,j; //不能设为全局变量
if(y>1&&square[x][y-1]!=1) //向左
{
for(j=y;j>=1&&square[x][j]==0;--j);
if(j>=1&&square[x][j]==3)
{
num
=min(num,c);
return ;
}
else if(j>=1&&square[x][j]==1)
{
square[x][j]
=0;
c
++;
if(c<=10)
dfs(x,j
+1);
square[x][j]
=1;
c
--;
}
}
if(x+1<=h&&square[x+1][y]!=1) //向下
{
for(i=x;i<=h&&square[i][y]==0;++i);
if(i<=h&&square[i][y]==3)
{
num
=min(num,c);
return ;
}
else if(i<=h&&square[i][y]==1)
{
square[i][y]
=0;
c
++;
if(c<=10)
dfs(i
-1,y);
square[i][y]
=1;
c
--;
}
}
if(y+1<=w&&square[x][y+1]!=1) //向右
{
for(j=y;j<=w&&square[x][j]==0;++j);
if(j<=w&&square[x][j]==3)
{
num
=min(num,c);
return ;
}
else if(j<=w&&square[x][j]==1)
{
square[x][j]
=0;
c
++;
if(c<=10)
dfs(x,j
-1);
square[x][j]
=1;
c
--;
}
}
if(x-1>=1&&square[x-1][y]!=1) //向上
{
for(i=x;i>=1&&square[i][y]==0;--i);
if(i>=1&&square[i][y]==3)
{
num
=min(num,c);
return ;
}
else if(i>=1&&square[i][y]==1)
{
square[i][y]
=0;
c
++;
if(c<=10)
dfs(i
+1,y);
square[i][y]
=1;
c
--;
}
}
}
int main()
{
int sx,sy;
while(cin>>w>>h&&w)
{
for(int i=1;i<=h;++i)
for(int j=1;j<=w;++j)
{
cin
>>square[i][j];
if(square[i][j]==2)
sx
=i,sy=j,square[i][j]=0;
}
c
=1;num=11;
dfs(sx,sy);
if(num==11)
cout
<<"-1\n";
else
cout
<<num<<endl;
}
return 0;
}

  

posted on 2011-07-22 19:53  sysu_mjc  阅读(119)  评论(0编辑  收藏  举报

导航