Skip to content

Commit b083bbb

Browse files
authored
Create execution-of-all-suffix-instructions-staying-in-a-grid.cpp
1 parent c7fc8f0 commit b083bbb

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
// Time: O(m)
2+
// Space: O(m)
3+
4+
class Solution {
5+
public:
6+
vector<int> executeInstructions(int n, vector<int>& startPos, string s) {
7+
static const unordered_map<char, pair<int, int>> directions = {
8+
{'U', {-1, 0}}, {'R', {0, 1}}, {'D', {1, 0}}, {'L', {0, -1}}
9+
};
10+
11+
int x0 = startPos[0], y0 = startPos[1];
12+
int x = 0, y = 0;
13+
vector<int> result(size(s));
14+
iota(rbegin(result), rend(result), 1);
15+
unordered_map<int, vector<int>> lookup_x, lookup_y;
16+
lookup_x[x0 - x].emplace_back(0);
17+
lookup_y[y0 - y].emplace_back(0);
18+
for (int i = 0; i < size(s); ++i) {
19+
const auto& [dx, dy] = directions.at(s[i]);
20+
x += dx, y += dy;
21+
for (const auto& k : {n - x, -x - 1}) {
22+
if (!lookup_x.count(k)) {
23+
continue;
24+
}
25+
for (const auto& j : lookup_x[k]) {
26+
result[j] = min(result[j], i - j);
27+
}
28+
lookup_x.erase(k);
29+
}
30+
for (const auto& k : {n - y, -y - 1}) {
31+
if (!lookup_y.count(k)) {
32+
continue;
33+
}
34+
for (const auto& j : lookup_y[k]) {
35+
result[j] = min(result[j], i - j);
36+
}
37+
lookup_y.erase(k);
38+
}
39+
lookup_x[x0 - x].emplace_back(i + 1);
40+
lookup_y[y0 - y].emplace_back(i + 1);
41+
}
42+
return result;
43+
}
44+
};

0 commit comments

Comments
 (0)