poj 3009
题意:给定一个m*n的网格,在这些网格上一些地方有障碍物,给定起点与终点的位置,当石头从起点开始走,撞上障碍才会转弯,否则会一直沿着来时的方向继续前进。撞到障碍后停在障碍前的位置,障碍消失。然后石头可以选择四个方向(相邻处无障碍的方向)前进,问至少需要停多少次才能从起点到达终点。不能到达或者多余10步后游戏失败。如果能到达输出最少的步数,否则输出-1.
dfs题目,有些难度,看懂了别人代码才写出来的,新手加油!
Memory: 5260k
Time: 1110MS
1 import java.util.Scanner; 2 3 public class Main{ 4 static int[][] map = new int[25][25]; //地图 5 static int w,h,sx,sy,gx,gy,flag,sumStep; //sx,sy,gx,gy 分别是起点和终点坐标,flag是否有路径标志,sumStep走的总步数 6 static int move[][]={{0,0,1,-1}, //移动方向 7 {1,-1,0,0}}; 8 9 public static boolean isIn(int x,int y,int w,int h){ 10 return x>=0&&x<h&&y>=0&&y<w; 11 } 12 13 public static void dfs(int x,int y,int step){ 14 int tx,ty; 15 if(step>=10) //步数大于10返回 16 return; 17 for(int i=0;i<4;i++){ //四个方向循环遍历 18 if(isIn(x+move[0][i],y+move[1][i],w,h) && map[x+move[0][i]][y+move[1][i]]!=1){ //判断即将遍历的点是否在界内,是否为障碍物 19 tx = x; 20 ty = y; 21 while(map[tx][ty]==0){ 22 tx+=move[0][i]; 23 ty+=move[1][i]; 24 if(tx==gx&&ty==gy){ 25 flag = 1; 26 if(sumStep>step+1) //sumStep保存最少步数 27 sumStep=step+1; 28 return; //到达终点返回 29 } 30 if(tx<0||tx>h||ty<0||ty>w) //判断越界 31 break; 32 } 33 if(tx>=0&&tx<h&&ty>=0&&ty<w&&step+1<=10){ //如果在界内,则tx,ty中是障碍物前停止的点,递归此点 34 map[tx][ty] = 0; //障碍物消除 35 dfs(tx-move[0][i],ty-move[1][i],step+1); 36 map[tx][ty] = 1; // 回溯,障碍物复原 37 } 38 } 39 } 40 } 41 42 public static void main(String[] args){ 43 Scanner in = new Scanner(System.in); 44 while(in.hasNext()){ 45 w = in.nextInt(); 46 h = in.nextInt(); 47 if(w==0&&h==0) 48 break; 49 for(int i=0;i<h;i++){ 50 for(int j=0;j<w;j++){ 51 map[i][j] = in.nextInt(); 52 if(map[i][j] == 2){ 53 sx = i; 54 sy = j; 55 map[i][j]=0; //记下起点后起点值置0 56 } 57 if(map[i][j] == 3){ 58 gx = i; 59 gy = j; 60 map[i][j]=0; //记下终点后终点值置0 61 } 62 } 63 } 64 flag = 0; 65 sumStep = 9999999; 66 dfs(sx,sy,0); 67 if(flag==0) 68 System.out.println("-1"); 69 else 70 System.out.println(sumStep); 71 } 72 } 73 }