来宾网站建设,手机网页代码,网站空间免费试用,电商网站开发平台一题目
874. 模拟行走机器人
题解思路
初始方向朝y轴正方向#xff0c;遇到指令command -1 则向右转#xff0c; 若为 -2 则向左转 定义方向[-1,0]、[0,1]、[1,0]、[0,-1] 分别为朝x轴负方向#xff0c; y轴正方向#xff0c; x轴正方向#xff0c;y轴负方向初始方向为[…题目
874. 模拟行走机器人
题解思路
初始方向朝y轴正方向遇到指令command -1 则向右转 若为 -2 则向左转 定义方向[-1,0]、[0,1]、[1,0]、[0,-1] 分别为朝x轴负方向 y轴正方向 x轴正方向y轴负方向初始方向为[0,1], 若向右转 则方向变为[-1,0]、若向左转方向变为[1,0]。若向右转则不断 向右递加 向左转则向左递减同时建立集合set 存储有障碍的点。set集合查询时间复杂度为o1
代码
C
class Solution {
public:int robotSim(vectorint commands, vectorvectorint obstacles) {int dirs[4][2] {{-1, 0}, {0, 1}, {1, 0}, {0, -1}};int sx 0, sy 0, res 0, d 1;setpairint, int mp;for(int i 0; i obstacles.size(); i){pairint, int t(obstacles[i][0], obstacles[i][1]);mp.insert(t);}for (int c : commands){if (c 0){d c -1 ? 1 : -1;d % 4;if (d 0){d 4;}}else{for (int i 0; i c; i){int nx sx dirs[d][0];int ny sy dirs[d][1];pairint, int t(nx, ny);if (mp.count(t)){break;}res max(res, nx * nx ny * ny);sx nx;sy ny;}}} return res;}
};Python
class Solution:def robotSim(self, commands: List[int], obstacles: List[List[int]]) - int:dirs [[-1, 0], [0, 1], [1, 0], [0, -1]]sx, sy 0, 0d 1res 0mp set([tuple(i) for i in obstacles])for c in commands:if c 0:d 1 if c -1 else -1d % 4else:for i in range(c):if tuple([sx dirs[d][0], sy dirs[d][1]]) in mp:breakelse:sx dirs[d][0]sy dirs[d][1]res max(res, sx*sx sy * sy)return res