Robot Room Cleaner - JAVA

Given a robot cleaner in a room modeled as a grid.
Each cell in the grid can be empty or blocked.
The robot cleaner with 4 given APIs can move forward, turn left or turn right. Each turn it made is 90 degrees.
When it tries to move into a blocked cell, its bumper sensor detects the obstacle and it stays on the current cell.
Design an algorithm to clean the entire room using only the 4 given APIs shown below.
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 turnLeft/turnRight.
  // Each turn will be 90 degrees.
  void turnLeft();
  void turnRight();

  // Clean the current cell.
  void clean();
}
Example:
Input:
room = [
  [1,1,1,1,1,0,1,1],
  [1,1,1,1,1,0,1,1],
  [1,0,1,1,1,1,1,1],
  [0,0,0,1,0,0,0,0],
  [1,1,1,1,1,1,1,1]
],
row = 1,
col = 3

Explanation:
All grids in the room are marked by either 0 or 1.
0 means the cell is blocked, while 1 means the cell is accessible.
The robot initially starts at the position of row=1, col=3.
From the top left corner, its position is one row below and three columns right.
Notes:
  1. The input is only given to initialize the room and the robot's position internally. You must solve this problem "blindfolded". In other words, you must control the robot using only the mentioned 4 APIs, without knowing the room layout and the initial robot's position.
  2. The robot's initial position will always be in an accessible cell.
  3. The initial direction of the robot will be facing up.
  4. All accessible cells are connected, which means the all cells marked as 1 will be accessible by the robot.
  5. Assume all four edges of the grid are all surrounded by wall.

We use a backtrack recursive method to solve this problem. Maintaining a hash set to contain the position that we have visited. Clean it up and add it into the set. Then for the four directions, move forward and continue backtrack, after that, return to original position and maintain original direction. then turn to another direction.

--------------------- 


We don't know the x,y co-ordinate. But we have to mark if we have reached a position before to avoid processing same state again and again (as we mark in standard DFS).
So, lets say current position is 0,0.
Then for every up move: x--
For every down move: x++
For every right move: y++
For every left move: y--
Most tricky part is:
when our recursive call will go back to last state, x,y,dir will be as before but robot's position is updated already. So, we have to move back the robot to earlier position with earlier direction!
class Solution {
    private Set<String> hasVisited;
    //private int direction; //0=UP, 1=RIGHT, 2=DOWN, 3=LEFT
    public void cleanRoom(Robot robot) {
        hasVisited = new HashSet<>();
        //assume current co-ordinate as (0,0)
        int x = 0;
        int y = 0;
        hasVisited.add(getCoOrdinate(x, y));
        //direction = 0;
        cleanRoomRecursively(robot, x, y, 0);
    }
    
    private void cleanRoomRecursively(Robot robot, int x, int y ,int direction){
        //System.out.println("x: " + x + " y: " + y + " d: "+ direction);
        robot.clean();
        //4 moves
        //go to same direction
        //System.out.println("straingt");
        goNextBlock(robot, direction, x, y);
        //go to 90
        //System.out.println("right");
        robot.turnRight();
        direction = (direction + 1) % 4;
        goNextBlock(robot, direction, x, y);
        
        //go to 180
        //System.out.println("back");
        robot.turnRight();
        direction = (direction + 1) % 4;
        goNextBlock(robot, direction, x, y);
        
        //go to 270
        //System.out.println("left");
        robot.turnRight();
        direction = (direction + 1) % 4;
        goNextBlock(robot, direction, x, y);
        
        //now it will go to the callee, which will have x, y and direction using which this 
        //function was called. But the robot has moved 270 degree and 1 block forward
        //So, put it back 1 block and face to the correct direction turn two time left or right in last it will turn 180
        robot.turnLeft();
        robot.move();
        robot.turnRight();
        robot.turnRight();
        //System.out.println("returning");
    }
    
    private void goNextBlock(Robot robot, int direction, int x, int y){
            switch (direction){
                case 0: x--;
                    break;
                case 1: y++;
                    break;
                case 2: x++;
                    break;
                case 3: y--;
                    break;
            };
            if(!hasVisited.contains(getCoOrdinate(x, y))){
                hasVisited.add(getCoOrdinate(x, y));
                if(robot.move()){
                    cleanRoomRecursively(robot, x, y, direction);        
                }
                
            }
        }
    
    private String getCoOrdinate(int x, int y){
        String coOrdinate = x + "," + y;
        //System.out.println(coOrdinate);
        return coOrdinate;
    }
}

Other solution
  1. To track the cells the robot has cleaned, start a index pair (i, j) from (0, 0). When go up, i-1; go down, i+1; go left, j-1; go right: j+1.
  2. Also use DIR to record the current direction of the robot
    public void cleanRoom(Robot robot) {
        // A number can be added to each visited cell
        // use string to identify the class
        Set<String> set = new HashSet<>();
        int cur_dir = 0;   // 0: up, 90: right, 180: down, 270: left
        backtrack(robot, set, 0, 0, 0);
    }

    public void backtrack(Robot robot, Set<String> set, int i, 
       int j, int cur_dir) {
     String tmp = i + "->" + j;
     if(set.contains(tmp)) {
            return;
        }
        
     robot.clean();
     set.add(tmp);

     for(int n = 0; n < 4; n++) {
        // the robot can to four directions, we use right turn
      if(robot.move()) {
       // can go directly. Find the (x, y) for the next cell based on current direction
       int x = i, y = j;
       switch(cur_dir) {
        case 0:
         // go up, reduce i
         x = i-1;
         break;
        case 90:
         // go right
         y = j+1;
         break;
        case 180:
         // go down
         x = i+1;
         break;
        case 270:
         // go left
         y = j-1;
         break;
        default:
         break;
       }

       backtrack(robot, set, x, y, cur_dir);
                       // go back to the starting position
   robot.turnLeft();
       robot.turnLeft();
       robot.move();
       robot.turnRight();
       robot.turnRight();

      } 
      // turn to next direction
      robot.turnRight();
      cur_dir += 90;
      cur_dir %= 360;
     }

    }

1 comment: