没什么好说的,模拟每一个即可。时间复杂度O(N), N为步数,代码如下:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
public: | |
int robotSim(vector<int>& commands, vector<vector<int>>& obstacles) { | |
unordered_set<string> obs; | |
for (const auto& obstacle : obstacles) | |
{ | |
string key = to_string(obstacle[0]) + "," + to_string(obstacle[1]); | |
obs.insert(key); | |
} | |
vector<pair<int, int>> dirs = { {0, 1}, {1, 0}, {0, -1}, {-1, 0} }; | |
int idx = 0, res = 0, currX = 0, currY = 0; | |
for (const int command : commands) | |
{ | |
if (command == -2) | |
idx = (idx + 3) % 4; | |
else if (command == -1) | |
idx = (idx + 1) % 4; | |
else | |
{ | |
for (int i = 0; i < command; ++i) | |
{ | |
int x = currX + dirs[idx].first, y = currY + dirs[idx].second; | |
string key = to_string(x) + "," + to_string(y); | |
if (obs.find(key) == obs.end()) | |
{ | |
currX = x; | |
currY = y; | |
res = max(res, x * x + y * y); | |
} | |
} | |
} | |
} | |
return res; | |
} | |
}; |
No comments:
Post a Comment