POJ 3009 Curling 2.0

解题思路:DFS

Bad
   
     
#include < iostream >
using namespace std;
int w, h, sx, sy, ex, ey, map[ 20 ][ 20 ];
const int dir[ 4 ][ 2 ] = { 0 , 1 , 1 , 0 , 0 , - 1 , - 1 , 0 };

inline
bool IsOk( int & x, int & y, int d)
{
int i,tx,ty;
for (tx = x,ty = y,i = 1 ;;i ++ ,tx = x,ty = y)
{
x
+= dir[d][ 0 ],y += dir[d][ 1 ];
if (x < 0 || x >= h || y < 0 || y >= w) return false ;
if (map[x][y] == 1 ){ if (i != 1 ){map[x][y] = 0 ;x = tx,y = ty; return true ;} return false ;}
if (map[x][y] == 3 )
return true ;
}
}

int DFS( int x, int y, int depth, int min)
{
int i,j,d,tx,ty,mind = 11 ;
if (depth > 10 || depth >= min)
return depth;
if (x == ex && y == ey)
return depth;
for (i = 0 ;i < 4 ;i ++ )
{
tx
= x, ty = y;
if (IsOk(tx, ty, i))
{
d
= DFS(tx, ty, depth + 1 ,mind);
if (tx != ex || ty != ey)
map[tx
+ dir[i][ 0 ]][ty + dir[i][ 1 ]] = 1 ;
if (mind > d)mind = d;
}
}
return mind;
}

int main()
{
int i,j,d;
while (scanf( " %d %d " , & w, & h) && (w + h))
{
for (i = 0 ;i < h;i ++ )
for (j = 0 ;j < w;j ++ )
{
scanf(
" %d " , & map[i][j]);
if (map[i][j] == 2 )sx = i,sy = j;
else if (map[i][j] == 3 )ex = i,ey = j;
}
d
= DFS(sx, sy, 0 , 11 );
d
> 10 ? printf( " -1\n " ):printf( " %d\n " ,d);
}
return 0 ;
}

 

你可能感兴趣的:(curl)