拼多多线下笔试/机器人寻址题目,思路分享,求助
题目:
3. 房间里面有一个机器人位于位置(0, 0)。房间的形状和面积都是未知的。你可以通过一个 遥控器来控制机器人往前后左右四个方向中的任何一个移动一个格子。 移动的函数是 boolean move(int direction), direction: 0, 1, 2, 3。如果机器人发现移动方向上被 墙壁挡住,这个方***返回 false,否则这个函数就会返回 true,机器人就会移动到相应的位 置。 请实现一个函数,来找到房间的面积。 注:房间的形状是不规则的,但是是由许多大小为 1x1 的格子组成的,比如下图表示的房子 里面,每一个 X 表示一个格子,房间的总面积是 10
X XXX X XXXXX
X XXX X XXXXX
思路分享/代码:
代码有点乱,肯定是跑不通的,思路是
1.因为不知道矩阵多大,用map+map存坐标和是否访问过
2.用回溯法来做这道题
不知道想法对不对,如果有兴趣的可以交流一下,多谢
import java.util.HashMap; import java.util.Map; /** * @Author:zhangzy * @Date:2017/11/18 */ public class test2 { public static int solution() { Map<Integer, Map<Integer, Boolean>> map = new HashMap<>(); return helper(0,0,map); } public static int helper(int x, int y, Map<Integer, Map<Integer, Boolean>> map){ int up = 0, down = 0,left = 0, right = 0; if(map.containsKey(x)){ if(map.get(x).containsKey(y)) { return 0; } else { map.get(x).put(y , true); } } else { Map<Integer ,Boolean> temp = new HashMap<>(); temp.put(y , true); map.put(x , temp); } if (move(0)) { up = helper(x - 1 , y ,map); } if (move(1)) { down = helper(x + 1 , y ,map); } if (move(2)) { left = helper(x , y - 1 ,map); } if (move(3)) { right = helper(x , y + 1 ,map); } return up + down + left + right + 1; } //这里只是声明一下 public static boolean move(int direction){ return true; } }