-
-
Notifications
You must be signed in to change notification settings - Fork 8.9k
/
Copy pathSolution.ts
41 lines (40 loc) · 1.23 KB
/
Solution.ts
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
/**
* class 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.
* move(): boolean {}
*
* // Robot will stay in the same cell after calling turnLeft/turnRight.
* // Each turn will be 90 degrees.
* turnRight() {}
*
* // Robot will stay in the same cell after calling turnLeft/turnRight.
* // Each turn will be 90 degrees.
* turnLeft() {}
*
* // Clean the current cell.
* clean(): {}
* }
*/
function cleanRoom(robot: Robot) {
const dirs = [-1, 0, 1, 0, -1];
const vis = new Set<string>();
const dfs = (i: number, j: number, d: number) => {
vis.add(`${i}-${j}`);
robot.clean();
for (let k = 0; k < 4; ++k) {
const nd = (d + k) % 4;
const [x, y] = [i + dirs[nd], j + dirs[nd + 1]];
if (!vis.has(`${x}-${y}`) && robot.move()) {
dfs(x, y, nd);
robot.turnRight();
robot.turnRight();
robot.move();
robot.turnRight();
robot.turnRight();
}
robot.turnRight();
}
};
dfs(0, 0, 0);
}