首页 > 代码库 > dfs/poj 3009 Curling 2.0

dfs/poj 3009 Curling 2.0

 1 #include<cstdio> 2 using namespace std; 3  4 const int dx[4]={0,1,0,-1}; 5 const int dy[4]={1,0,-1,0}; 6  7 int m,n,ans,ex,ey,sx,sy; 8 int a[22][22]; 9 10 int cmin(int a,int b) {return a<b?a:b;}11 12 bool pd(int xx,int yy)13 {14     if (xx>=1 && xx<=n && yy>=1 && yy<=m) return true;15     return false;16 }17 18 void dfs(int x,int y,int step)19 {20     if (step>10 || step>=ans ) return ;21 22     for (int i=0;i<4;i++)23     {24         int xx=x+dx[i],yy=y+dy[i];25         if (a[xx][yy]==1) continue;26         while (1)27         {28             if (!pd(xx,yy)) break;29             if (a[xx][yy]==1)30             {31                 a[xx][yy]=0;32                 dfs(xx-dx[i],yy-dy[i],step+1);33                 a[xx][yy]=1;34                 break;35             }36             else if (a[xx][yy]==3)37             {38                 ans=cmin(ans,step+1);39                 return;40             }41             xx+=dx[i];yy+=dy[i];42         }43     }44     return;45 }46 47 int main()48 {49     scanf("%d%d",&m,&n);50     while (m!=0)51     {52         for (int i=1;i<=n;i++)53             for (int j=1;j<=m;j++)54             {55                 scanf("%d",&a[i][j]);56                 if (a[i][j]==2){sx=i;sy=j;a[i][j]=0;}57             }58 59         ans=11;60         dfs(sx,sy,0);61         if (ans>10) printf("-1\n");62         else printf("%d\n",ans);63 64         scanf("%d%d",&m,&n);65     }66     return 0;67 }

 

dfs/poj 3009 Curling 2.0