LeetCode Solutions
874. Walking Robot Simulation
Time: $O(9 \cdot |\texttt{commands}| + |\texttt{obstacles}|) = O(|\texttt{commands}| + |\texttt{obstacles}|)$ Space: $O(|\texttt{obstacles}|)$
class Solution {
public:
int robotSim(vector<int>& commands, vector<vector<int>>& obstacles) {
const vector<int> dirs{0, 1, 0, -1, 0};
int ans = 0;
int d = 0; // 0 := north, 1 := east, 2 := south, 3 := west
int x = 0; // Start x
int y = 0; // Start y
unordered_set<pair<int, int>, pairHash> obstaclesSet;
for (const vector<int>& o : obstacles)
obstaclesSet.insert({o[0], o[1]});
for (const int c : commands) {
if (c == -1) {
d = (d + 1) % 4;
} else if (c == -2) {
d = (d + 3) % 4;
} else {
for (int step = 0; step < c; ++step) {
if (obstaclesSet.count({x + dirs[d], y + dirs[d + 1]}))
break;
x += dirs[d];
y += dirs[d + 1];
}
}
ans = max(ans, x * x + y * y);
}
return ans;
}
private:
struct pairHash {
size_t operator()(const pair<int, int>& p) const {
return p.first ^ p.second;
}
};
};
class Solution {
public int robotSim(int[] commands, int[][] obstacles) {
final int[] dirs = {0, 1, 0, -1, 0};
int ans = 0;
int d = 0; // 0 := north, 1 := east, 2 := south, 3 := west
int x = 0; // Start x
int y = 0; // Start y
Set<Pair<Integer, Integer>> obstaclesSet = new HashSet<>();
for (int[] o : obstacles)
obstaclesSet.add(new Pair<>(o[0], o[1]));
for (final int c : commands) {
if (c == -1) {
d = (d + 1) % 4;
} else if (c == -2) {
d = (d + 3) % 4;
} else {
for (int step = 0; step < c; ++step) {
if (obstaclesSet.contains(new Pair<>(x + dirs[d], y + dirs[d + 1])))
break;
x += dirs[d];
y += dirs[d + 1];
}
}
ans = Math.max(ans, x * x + y * y);
}
return ans;
}
}
class Solution:
def robotSim(self, commands: List[int], obstacles: List[List[int]]) -> int:
dirs = [0, 1, 0, -1, 0]
ans = 0
d = 0 # 0 := north, 1 := east, 2 := south, 3 := west
x = 0 # Start x
y = 0 # Start y
obstaclesSet = {(x, y) for x, y in obstacles}
for c in commands:
if c == -1:
d = (d + 1) % 4
elif c == -2:
d = (d + 3) % 4
else:
for _ in range(c):
if (x + dirs[d], y + dirs[d + 1]) in obstaclesSet:
break
x += dirs[d]
y += dirs[d + 1]
ans = max(ans, x * x + y * y)
return ans