Advertisement
lifeiteng

489. Robot Room Cleaner

Sep 25th, 2018
88
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.58 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 Solution {
  19.     public void cleanRoom(Robot robot) {
  20.         dfs(robot, 0, 0, 0);
  21.     }
  22.    
  23.     void dfs(Robot robot, int i, int j, int dir)
  24.     {
  25.         if(map.containsKey(i) && map.get(i).contains(j)) return;
  26.         // System.out.printf("%d %d %d\n", i, j, dir);
  27.         if(!map.containsKey(i)) map.put(i, new HashSet<>());
  28.         map.get(i).add(j);
  29.         robot.clean();
  30.         int[] dx = {-1, 0, 1, 0}, dy = {0, -1, 0, 1};
  31.         // try 4 different directions
  32.         for(int k = 0; k < 4; k++)
  33.         {
  34.             if(robot.move())
  35.             {
  36.                 dfs(robot, i + dx[dir], j + dy[dir], dir);
  37.                 robot.turnLeft();
  38.                 robot.turnLeft();
  39.                 robot.move();
  40.                 robot.turnLeft();
  41.                 robot.turnLeft();
  42.             }    
  43.            
  44.             robot.turnLeft();
  45.             dir = (dir + 1) % 4;
  46.         }
  47.     }
  48.    
  49.     Map<Integer, Set<Integer>> map = new HashMap<>();
  50. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement