POJ 3009 Curling 2.0

  
    
#include < stdio.h >
#define MAXN 21
int map[MAXN][MAXN];
int startx, starty;
int w, h, ok, minMove;
int dr[ 4 ][ 2 ] = {{ 1 , 0 },{ - 1 , 0 },{ 0 , 1 },{ 0 , - 1 }};
int legal( int x, int y){
if (x >= 1 && y >= 1 && x <= h && y <= w )
return 1 ;
return 0 ;
}
void in (){
int i, j;
for (i = 1 ; i <= h; ++ i){
for (j = 1 ; j <= w; ++ j){
scanf(
" %d " , & map[i][j]);
if (map[i][j] == 2 ){
startx
= i;
starty
= j;
map[i][j]
= 0 ;
}
}
}
}
void DFS( int x, int y, int move){
int d,nx,ny;
if (move >= minMove){
return ;
}
for (d = 0 ; d < 4 ; d ++ ){
nx
= x;
ny
= y;
while ( 1 ){   //要注意的地方
nx
+= dr[d][ 0 ];
ny
+= dr[d][ 1 ];
if ( ! legal(nx, ny) || map[nx][ny] == 1 ){
  
break ;
}
if (map[nx][ny] == 0 && map[nx + dr[d][ 0 ]][ny + dr[d][ 1 ]] == 1 ){
map[nx
+ dr[d][ 0 ]][ny + dr[d][ 1 ]] = 0 ;
     DFS(nx,ny,move
+ 1 );
map[nx
+ dr[d][ 0 ]][ny + dr[d][ 1 ]] = 1 ;
break ;
}
if (map[nx][ny] == 3 ){
if (move < minMove){
minMove
= move;
ok
= 1 ;
break ;
}
}
}
}

}
int main(){

int i, j;
while (scanf( " %d%d " , & w, & h) == 2 , w + h){
memset(map,
0 , sizeof (map));
in ();
ok
= 0 ;
minMove
= 11 ;
DFS(startx, starty,
1 );
if ( ok )
printf(
" %d\n " ,minMove);
else
printf(
" -1\n " );
}
return 0 ;
}

你可能感兴趣的:(curl)