-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathP_489.java
More file actions
43 lines (34 loc) · 1.01 KB
/
Copy pathP_489.java
File metadata and controls
43 lines (34 loc) · 1.01 KB
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
package leetcode.hard;
import java.util.HashSet;
import java.util.Set;
public class P_489 {
interface Robot {
boolean move();
void turnRight();
void clean();
}
private static final int[][] DIRS = { { 0, 1 }, { 1, 0 }, { 0, -1 }, { -1, 0 } };
public void cleanRoom(Robot robot) {
dfs(0, 0, 0, new HashSet<>(), robot);
}
public void dfs(int x, int y, int d, Set<String> visited, Robot robot) {
robot.clean();
for (int i = 0; i < 4; i++) {
final int newD = (i + d) % 4;
final int newX = x + DIRS[newD][0];
final int newY = y + DIRS[newD][1];
if (visited.add(newX + "," + newY) && robot.move()) {
dfs(newX, newY, newD, visited, robot);
}
robot.turnRight();
}
back(robot);
}
public void back(Robot robot) {
robot.turnRight();
robot.turnRight();
robot.move();
robot.turnRight();
robot.turnRight();
}
}