-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path0874-walking-robot-simulation.cpp
82 lines (77 loc) · 2.31 KB
/
0874-walking-robot-simulation.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
class Solution {
public:
int robotSim(vector<int>& commands, vector<vector<int>>& obstacles) {
set<pair<int, int>> ob;
for (auto& i : obstacles) {
ob.insert({i[0], i[1]});
}
auto haveOb = [&](int x, int y) {
return (ob.find({x, y}) != ob.end());
};
auto fixDir = [&](int x, char dir) {
if (x == -1) {
if (dir == 'u') dir = 'r';
else if (dir == 'r') dir = 'd';
else if (dir == 'd') dir = 'l';
else if (dir == 'l') dir = 'u';
} else if (x == -2) {
if (dir == 'u') dir = 'l';
else if (dir == 'l') dir = 'd';
else if (dir == 'd') dir = 'r';
else if (dir == 'r') dir = 'u';
}
return dir;
};
auto getMx = [&](int x, int y) {
return x * x + y * y;
};
int x = 0, y = 0;
char dir = 'u';
int mx = 0;
for (auto& i : commands) {
if (i < 0) {
dir = fixDir(i, dir);
continue;
}
int cur = i;
if (dir == 'u') {
while (cur) {
y++, cur--;
if (haveOb(x, y)) {
y--;
break;
}
mx = max(mx, getMx(x, y));
}
} else if (dir == 'r') {
while (cur) {
x++, cur--;
if (haveOb(x, y)) {
x--;
break;
}
mx = max(mx, getMx(x, y));
}
} else if (dir == 'd') {
while (cur) {
y--, cur--;
if (haveOb(x, y)) {
y++;
break;
}
mx = max(mx, getMx(x, y));
}
} else if (dir == 'l') {
while (cur) {
x--, cur--;
if (haveOb(x, y)) {
x++;
break;
}
mx = max(mx, getMx(x, y));
}
}
}
return mx;
}
};