-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0489-robot-room-cleaner.js
More file actions
39 lines (33 loc) · 1.36 KB
/
0489-robot-room-cleaner.js
File metadata and controls
39 lines (33 loc) · 1.36 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
/**
* Robot Room Cleaner
* Time Complexity: O(R * C)
* Space Complexity: O(R * C)
*/
var cleanRoom = function (robot) {
const visitedLocations = new Set();
const directionVectors = [[-1, 0], [0, 1], [1, 0], [0, -1]];
exploreAndClean(0, 0, 0);
function exploreAndClean(currentRowPosition, currentColumnPosition, currentDirectionState) {
const cellIdentifier = `${currentRowPosition},${currentColumnPosition}`;
if (visitedLocations.has(cellIdentifier)) {
return;
}
visitedLocations.add(cellIdentifier);
robot.clean();
for (let iterationCounter = 0; iterationCounter < 4; iterationCounter++) {
const nextAbsoluteDirection = (currentDirectionState + iterationCounter) % 4;
const [deltaRowMovement, deltaColumnMovement] = directionVectors[nextAbsoluteDirection];
const nextRowCoordinate = currentRowPosition + deltaRowMovement;
const nextColumnCoordinate = currentColumnPosition + deltaColumnMovement;
if (robot.move()) {
exploreAndClean(nextRowCoordinate, nextColumnCoordinate, nextAbsoluteDirection);
robot.turnRight();
robot.turnRight();
robot.move();
robot.turnLeft();
robot.turnLeft();
}
robot.turnRight();
}
}
};