Skip to content

Commit 33ec853

Browse files
committed
Added 1 solution
1 parent 08d4dc5 commit 33ec853

File tree

1 file changed

+63
-0
lines changed

1 file changed

+63
-0
lines changed

Hard/Robot Room Cleaner.java

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
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+
Set<String> visited = new HashSet<>();
21+
backtrack(robot, visited, 0, 0, 0);
22+
}
23+
24+
private void backtrack(Robot robot, Set<String> visited, int x, int y, int dir) {
25+
String key = x + "|" + y;
26+
if (visited.contains(key)) {
27+
return;
28+
}
29+
30+
visited.add(key);
31+
robot.clean();
32+
33+
for (int k = 0; k < 4; k++) {
34+
int i = x;
35+
int j = y;
36+
if (robot.move()) {
37+
if (dir == 0) {
38+
i = x - 1;
39+
}
40+
else if (dir == 1) {
41+
j = y + 1;
42+
}
43+
else if (dir == 2) {
44+
i = x + 1;
45+
}
46+
else {
47+
j = y - 1;
48+
}
49+
50+
backtrack(robot, visited, i, j, dir);
51+
robot.turnLeft();
52+
robot.turnLeft();
53+
robot.move();
54+
robot.turnRight();
55+
robot.turnRight();
56+
}
57+
58+
robot.turnRight();
59+
dir += 1;
60+
dir %= 4;
61+
}
62+
}
63+
}

0 commit comments

Comments
 (0)