Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * // This is the robot's control interface.
- * // You should not implement it, or speculate about its implementation
- * interface Robot {
- * // Returns true if the cell in front is open and robot moves into the cell.
- * // Returns false if the cell in front is blocked and robot stays in the current cell.
- * public boolean move();
- *
- * // Robot will stay in the same cell after calling turnLeft/turnRight.
- * // Each turn will be 90 degrees.
- * public void turnLeft();
- * public void turnRight();
- *
- * // Clean the current cell.
- * public void clean();
- * }
- */
- class Coord {
- int r, c;
- Coord (int r, int c) {
- this.r = r;
- this.c = c;
- }
- @Override
- public int hashCode() {
- return r * 1000 + c;
- }
- @Override
- public boolean equals(Object other) {
- Coord coord = (Coord) other;
- return coord.r == r && coord.c == c;
- }
- @Override
- public String toString() {
- return "<" + r + ", " + c + ">";
- }
- }
- class Solution {
- int[] rows = {-1, 0, 1, 0};
- int[] columns = {0, 1, 0, -1};
- // Direction-> 0: Up, 1: Right, 2: Down, 3: Left
- public void cleanRoom(Robot robot) {
- dfs(new HashSet<Coord>(), robot, 0, new Coord(0, 0));
- }
- private void goBack(Robot robot) {
- robot.turnRight();
- robot.turnRight();
- // turn 180 degree
- robot.move();
- // move forward
- robot.turnRight();
- robot.turnRight();
- // turn 180 degree again
- }
- private void dfs(HashSet<Coord> visited, Robot robot, int direction, Coord currentCoord){
- if(visited.contains(currentCoord)) return;
- visited.add(currentCoord);
- robot.clean();
- // clean the current cell.
- for (int i = 0; i < 4; i++) {
- int newDirection = (direction + i) % 4;
- int newRow = currentCoord.r + rows[newDirection];
- int newCol = currentCoord.c + columns[newDirection];
- if (robot.move()) {
- dfs(visited, robot, newDirection, new Coord(newRow, newCol));
- goBack(robot);
- }
- robot.turnRight();
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement