-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwalking-robot-simulation.cpp
More file actions
80 lines (66 loc) · 1.96 KB
/
walking-robot-simulation.cpp
File metadata and controls
80 lines (66 loc) · 1.96 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
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
// 874. Walking Robot Simulation (11/30/57677)
// Runtime: 27 ms (59.85%) Memory: 37.83 MB (55.96%)
class Solution {
struct Cell
{
int x;
int y;
bool operator<(const Cell& other) const
{
if (x != other.x) return x < other.x;
return y < other.y;
}
};
public:
int robotSim(vector<int>& commands, vector<vector<int>>& obstacles) {
for(const auto& o : obstacles)
{
{
obst.insert({o[0], o[1]});
}
}
const auto COMM_SIZE = commands.size();
int maxDistanceSquared = 0;
int dir = 0;
Cell curr{0,0};
bool start = true;
for(const auto& command: commands)
{
if(command == -1)
{
dir = ++dir % 4; // turn right
continue;
}
if(command == -2)
{
dir = (--dir + 4) % 4; // turn left
continue;
}
if(command >= 1 && command <=9)
{
for(int i=0; i < command; ++i)
{
const auto& [dx, dy] = DIRS[dir];
const Cell next{curr.x + dx, curr.y + dy};
// if not running into obstacle, then increment the cell
if(obst.find(next) == obst.end())
{
curr = next;
// Update max distance squared at each step
int currentDistSq = curr.x * curr.x + curr.y * curr.y;
maxDistanceSquared = std::max(maxDistanceSquared, currentDistSq);
}
else
{
break;
}
}
}
}
return maxDistanceSquared;
}
private:
std::vector<Cell> DIRS = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
// std::set<Cell> processed;
std::set<Cell> obst;
};