-
Notifications
You must be signed in to change notification settings - Fork 37
/
Copy path489. Robot Room Cleaner.cpp
88 lines (81 loc) · 2.16 KB
/
489. Robot Room Cleaner.cpp
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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
/**
* // This is the robot's control interface.
* // You should not implement it, or speculate about its implementation
* class Robot {
* public:
* // 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.
* bool move();
*
* // Robot will stay in the same cell after calling turnLeft/turnRight.
* // Each turn will be 90 degrees.
* void turnLeft();
* void turnRight();
*
* // Clean the current cell.
* void clean();
* };
*/
class Solution {
public:
void cleanRoom(Robot& robot) {
unordered_set<string>visited;
dfs(robot, 0, 0, visited);
}
// Robot always facing UP
void dfs(Robot& R, int r, int c, unordered_set<string>& visited) {
if (visited.count(tostr(r, c))) {
return;
}
R.clean();
visited.insert(tostr(r, c));
// Go through each direction, robot ALWAYS ends with UP
// Up
if (R.move()) {
dfs(R, r - 1, c, visited);
R.turnLeft();
R.turnLeft();
R.move();
R.turnLeft();
R.turnLeft();
}
// Left
R.turnLeft();
if (R.move()) {
R.turnRight();
dfs(R, r, c - 1, visited);
R.turnRight();
R.move();
R.turnLeft();
R.turnLeft();
}
R.turnRight();
// Right
R.turnRight();
if (R.move()) {
R.turnLeft();
dfs(R, r, c + 1, visited);
R.turnLeft();
R.move();
R.turnLeft();
R.turnLeft();
}
R.turnLeft();
// Down
R.turnLeft();
R.turnLeft();
if (R.move()) {
R.turnLeft();
R.turnLeft();
dfs(R, r + 1, c, visited);
R.move();
R.turnLeft();
R.turnLeft();
}
R.turnLeft();
R.turnLeft();
}
string tostr(int r, int c) {
return to_string(r) + "," + to_string(c);
}
};