题目描述
机器人在一个无限大小的网格上行走,从点 (0, 0) 处开始出发,面向北方。该机器人可以接收以下三种类型的命令:
-2:向左转 90 度
-1:向右转 90 度
1 <= x <= 9:向前移动 x 个单位长度
在网格上有一些格子被视为障碍物。
第 i 个障碍物位于网格点 (obstacles[i][0], obstacles[i][1])
如果机器人试图走到障碍物上方,那么它将停留在障碍物的前一个网格方块上,但仍然可以继续该路线的其余部分。
返回从原点到机器人的最大欧式距离的平方。
示例 1:
示例 2:
输入: commands = [4,-1,4,-2,4], obstacles = [[2,4]]
输出: 65
解释: 机器人在左转走到 (1, 8) 之前将被困在 (1, 4) 处
提示:
0 <= commands.length <= 10000
0 <= obstacles.length <= 10000
-30000 <= obstacle[i][0] <= 30000
-30000 <= obstacle[i][1] <= 30000
答案保证小于 2 ^ 31
解题思路
注意题目描述有漏洞:应该说是过程中最大的欧式平方
class Solution {
public:
int robotSim(vector<int>& commands, vector<vector<int>>& obstacles) {
int y=0;
int x=0;
int maxx=-1;
int dir=1;
for(int i=0;i<commands.size();i++){
if(commands[i]>0){
if(dir==1){
int yt = y + commands[i];
for(int j=0;j<obstacles.size();j++){
if(obstacles[j][0]==x && (obstacles[j][1]>y && obstacles[j][1]<=yt)){
yt = obstacles[j][1]-1;
}
}
y = yt;
}else if(dir == 2){
int xt = x+commands[i];
for(int j=0;j<obstacles.size();j++){
if(obstacles[j][1]==y && (obstacles[j][0]>x && obstacles[j][0]<=xt)){
xt = obstacles[j][0]-1;
}
}
x = xt;
}else if(dir==3){
int yt = y - commands[i];
for(int j=0;j<obstacles.size();j++){
if(obstacles[j][0]==x && (obstacles[j][1]<y && obstacles[j][1]>=yt)){
yt = obstacles[j][1]+1;
}
}
y = yt;
}else if(dir==4){
int xt = x-commands[i];
for(int j=0;j<obstacles.size();j++){
if(obstacles[j][1]==y && (obstacles[j][0]<x && obstacles[j][0]>=xt)){
xt = obstacles[j][0]+1;
}
}
x = xt;
}
}else if(commands[i]==-1){
if(dir==4){
dir = 1;
}else{
dir++;
}
}else if(commands[i]==-2){
if(dir==1){
dir = 4;
}else{
dir--;
}
}
maxx = max(maxx,x*x+y*y);
}
return maxx;
}
};
- 官方思路,使用set容器避免遍历查询障碍物,效率提升10倍,好活
class Solution {
public:
int robotSim(vector<int>& commands, vector<vector<int>>& obstacles) {
int dx[4] = {0, 1, 0, -1};
int dy[4] = {1, 0, -1, 0};
int x = 0, y = 0, di = 0;
set<pair<int, int>> obstacleSet;
for (vector<int> obstacle: obstacles)
obstacleSet.insert(make_pair(obstacle[0], obstacle[1]));
int ans = 0;
for (int cmd: commands) {
if (cmd == -2)
di = (di + 3) % 4;
else if (cmd == -1)
di = (di + 1) % 4;
else {
for (int k = 0; k < cmd; ++k) {
int nx = x + dx[di];
int ny = y + dy[di];
if (obstacleSet.find(make_pair(nx, ny)) == obstacleSet.end()) {
x = nx;
y = ny;
ans = max(ans, x*x + y*y);
}
}
}
}
return ans;
}
};