注册一亩三分地论坛,查看更多干货!
您需要 登录 才可以下载或查看附件。没有帐号?注册账号 
x
下周狗家店面,这两天就在地里刷面经,这道扫地机器人看到了好几次,就在google doc上写了一下。原题是这样的:
Given a robot cleaner in a room modeled as a grid. Each cell in the grid can be empty or blocked. The robot cleaner can move forward, turn left or turn right. When it tries to move into a blocked cell, its bumper sensor detects the obstacle and it stays on the current cell.
interface Robot { // returns true if next cell is open and robot moves into the cell. // returns false if next cell is obstacle and robot stays on the current cell. boolean Move(); // Robot will stay on the same cell after calling Turn*. k indicates how // many turns to perform. void TurnLeft(int k); void TurnRight(int k);
// Clean the current cell. void Clean();
boolean Move(Direction d); }
我理解这道题应该是让你写一个类去实现这个interface,也就是通过重写里面的方法来让机器人扫遍整个屋子。因为不知道起始位置在哪,我就用了一个HashSet来记录检测过的位置,然后用DFS + backtracking来扫描。我感觉这里还涉及到了一些跟硬件有关的API面试官没有写出来,比如说在物理上移动机器人,转向,检测障碍等等,这个没有给写不了,所以只能在相应位置标注一下了。 下面是我写的代码,没有实测,也不知道哪里有bug,贴出来大家提提问题。
- Public class Roomba implements Robot{
- Direction direction;
- Set<String> seen;
- int x; int y;
- Sensor sensor; //Sensor API to detect obstacle;
-
- class Direction{
- final int[][] dirs = {{0, -1}, {-1, 0}, {0, 1}, {1, 0}};
- int dir;
-
- public Direction(){
- int dir = 0;
- }
- public void turnL(){
- dir = (dir + 3) % 4;
- }
-
- public void turnR(){
- dir = (dir + 1) % 4;
- }
- }
-
- public Roomba(){
- direction = new Direction();
- seen = new HashSet<>();
- x = 0; y = 0;
- clean();
- seen.add(x+”,”+y);
- sensor = new Sensor();
- }
- boolean move(){
- x += direction.dirs[direction.dir][0];
- y += direction.dirs[direction.dir][1];
- seen.add(x+”,”+y);
- if(sensor.detect()){
- /*code to move the roomba physically move forward*/
- clean();
- return true;
- }else return false;
- }
- public void moveBack(){
- TurnRight(2);
- move();
- TurnRight(2);
- }
- void TurnLeft(int k){
- for(int i = 0; i < k; i++)
- direction.turnL();
- }
- void TurnRight(int k){
- for(int i = 0; i < k; i++)
- direction.turnL();
- }
- void Clean(){
- /*code to call the robot physically clean the current area */
- }
- public void sweep(){
- Direction prevDir = direction;
- for(int i = 0; i < 4; i++){
- TurnRight(1);
- int nextx = x + direction.dirs[direction.dir][0];
- int nexty = y + direction.dirs[direction.dir][1];
- if(seen.contains(nextx+”,”+nexty)) continue;
- if(move()){
- sweep();
- }
- }
- direction = prevDir;
- moveBack();
- }
- }
复制代码
|