用到了回溯。 具体步骤是这样的: 1、计算当前位置可以前进的方向。可以前进的判断方式是:该方向的下一个位置没有到达过 且 该方向的下一个位置没有障碍。使用Set存储机器人到达过的位置。 2、遍历可以前进的方向,递归进行试探,边界条件是:当前位置没有可以移动的方向。此时跳出该层,回溯到上一个位置,向上一个位置的另一个可移动方向进行试探。 3、递归结束后,计算Set中元素的个数,即为房间的面积。 代码亲测可用。 import java.util.*; public class Main{ static int x=0,y=0;//初始机器人位置     public static boolean move (int dir){//为了测试,自己写了一个move方法,比较片面         int[][] array= {//地图矩阵                 {0,0,0,0,0,0,0,1,1,1,1,1},                 {0,0,0,0,1,1,1,1,1,1,1,1},                 {0,0,0,0,0,0,1,1,1,1,1,1},                 {0,0,0,0,0,0,0,0,0,1,1,1},                 {0,0,0,0,0,0,0,1,1,1,1,1},                 {0,0,0,0,1,1,1,1,1,1,1,1}         };         int x_m=array.length;         int y_m=array[0].length;         switch(dir) {         case 0:             if(y+1>=y_m || array[x][y+1]!=0) {                 return false;             }             y++;             break;         case 1:             if(x+1>=x_m || array[x+1][y]!=0) {                 return false;             }             x++;             break;         case 2:             if(y-1<0 || array[x][y-1]!=0) {                 return false;             }             y--;             break;         case 3:             if(x-1<0 || array[x-1][y]!=0) {                 return false;             }             x--;             break;         default:             break;         }         return true;     } //计算面积的函数 public static int problem3 (int x,int y,Set<String> set){         set.add(x+","+y); //如果方向0的位置未到达过,且该位置没有障碍物,则移动到该位置。         if(!set.contains(x+","+(y+1)) && move(0)) {             problem3 (x,y+1,set);//迭代计算下一个位置的情况             move(2);//回溯         }         if(!set.contains((x+1)+","+y) && move(1)) {             problem3 (x+1,y,set);             move(3);         }         if(!set.contains(x+","+(y-1)) && move(2)) {             problem3 (x,y-1,set);             move(0);         }         if(!set.contains((x-1)+","+y) && move(3)) {             problem3 (x-1,y,set);             move(1);         }         return set.size();     } public static void main(String[] String){ Set<String> set=new HashSet<String>(); System.out.println(problem3(0,0,set)); } }
点赞 2

相关推荐

牛客网
牛客网在线编程
牛客网题解
牛客企业服务