-
Notifications
You must be signed in to change notification settings - Fork 28
/
Copy pathRobot_Room_Cleaner.cpp
58 lines (52 loc) · 1.48 KB
/
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
/**
* // 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 {
unordered_map<int, unordered_map<int, int>> grid;
int dx[4] = {-1, 0, 1, 0};
int dy[4] = {0, 1, 0, -1};
int x = 0, y = 0;
int dir = 0;
void setback(Robot& robot) {
robot.turnRight();
robot.turnRight();
robot.move();
robot.turnRight();
robot.turnRight();
}
public:
void cleanRoom(Robot& robot) {
if(grid[x][y] == 1) {
return;
}
robot.clean();
grid[x][y] = 1;
for (int i = 0; i < sizeof(dx) / sizeof(dx[0]); i++) {
if (robot.move()) {
x += dx[dir];
y += dy[dir];
cleanRoom(robot);
setback(robot);
x -= dx[dir];
y -= dy[dir];
}
robot.turnRight();
dir = (dir + 1) % 4;
}
}
};