05 August 2008
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
/**
* // 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 Solution {
private static final int[][] directions = { {-1, 0}, {0, 1}, {1, 0}, {0, -1} };
public void cleanRoom(Robot robot) {
clean(robot, 0, 0, 0, new HashSet<>());
}
private void clean(Robot robot, int x, int y, int curDirection, Set<String> visited) {
// Cleans current cell.
robot.clean();
visited.add(x + " " + y);
for (int nDirection = curDirection;
nDirection < curDirection + 4;
nDirection++) {
int nx = directions[nDirection % 4][0] + x;
int ny = directions[nDirection % 4][1] + y;
if (!visited.contains(nx + " " + ny) && robot.move()) {
clean(robot, nx, ny, nDirection % 4, visited);
}
// Changed orientation.
robot.turnRight();
}
// Moves backward one step while maintaining the orientation.
robot.turnRight();
robot.turnRight();
robot.move();
robot.turnRight();
robot.turnRight();
}
}