Advertisement
FNSY

489. Robot Room Cleaner

May 8th, 2022
852
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.25 KB | None | 0 0
  1. /**
  2.  * // This is the robot's control interface.
  3.  * // You should not implement it, or speculate about its implementation
  4.  * interface Robot {
  5.  *     // Returns true if the cell in front is open and robot moves into the cell.
  6.  *     // Returns false if the cell in front is blocked and robot stays in the current cell.
  7.  *     public boolean move();
  8.  *
  9.  *     // Robot will stay in the same cell after calling turnLeft/turnRight.
  10.  *     // Each turn will be 90 degrees.
  11.  *     public void turnLeft();
  12.  *     public void turnRight();
  13.  *
  14.  *     // Clean the current cell.
  15.  *     public void clean();
  16.  * }
  17.  */
  18.  class Coord {
  19.     int r, c;
  20.  
  21.     Coord (int r, int c) {
  22.         this.r = r;
  23.         this.c = c;
  24.     }
  25.  
  26.     @Override
  27.     public int hashCode() {
  28.         return r * 1000 + c;
  29.     }
  30.  
  31.     @Override
  32.     public boolean equals(Object other) {
  33.         Coord coord = (Coord) other;
  34.         return coord.r == r && coord.c == c;
  35.     }
  36.      
  37.      @Override
  38.      public String toString() {
  39.          return "<" + r + ", " + c + ">";
  40.      }
  41. }
  42.  
  43. class Solution {
  44.      
  45.     int[] rows = {-1, 0, 1, 0};
  46.     int[] columns = {0, 1, 0, -1};
  47.     // Direction-> 0: Up, 1: Right, 2: Down, 3: Left
  48.    
  49.     public void cleanRoom(Robot robot) {
  50.         dfs(new HashSet<Coord>(), robot, 0, new Coord(0, 0));
  51.     }
  52.       private void goBack(Robot robot) {
  53.        
  54.         robot.turnRight();
  55.         robot.turnRight();
  56.         // turn 180 degree
  57.         robot.move();
  58.         // move forward
  59.         robot.turnRight();
  60.         robot.turnRight();
  61.         // turn 180 degree again
  62.       }
  63.  
  64.     private void dfs(HashSet<Coord> visited, Robot robot, int direction, Coord currentCoord){
  65.  
  66.         if(visited.contains(currentCoord)) return;
  67.         visited.add(currentCoord);
  68.         robot.clean();
  69.         // clean the current cell.
  70.        
  71.         for (int i = 0; i < 4; i++) {
  72.            int newDirection = (direction + i) % 4;
  73.            int newRow = currentCoord.r + rows[newDirection];
  74.            int newCol = currentCoord.c + columns[newDirection];
  75.            if (robot.move()) {
  76.                 dfs(visited, robot, newDirection, new Coord(newRow, newCol));
  77.                 goBack(robot);
  78.            }
  79.            robot.turnRight();
  80.         }
  81.     }
  82.                    
  83. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement