題目
874. 模擬行走機器人文章來源地址http://www.zghlxwxcb.cn/news/detail-642858.html
題解思路
- 初始方向朝y軸正方向,遇到指令command == -1 則向右轉(zhuǎn), 若為 -2 則向左轉(zhuǎn)
- 定義方向[-1,0]、[0,1]、[1,0]、[0,-1] 分別為朝x軸負(fù)方向, y軸正方向, x軸正方向,y軸負(fù)方向
- 初始方向為[0,1], 若向右轉(zhuǎn) 則方向變?yōu)閇-1,0]、若向左轉(zhuǎn)方向變?yōu)閇1,0]。
- 若向右轉(zhuǎn)則不斷 向右遞加, 向左轉(zhuǎn)則向左遞減
- 同時建立集合set 存儲有障礙的點。(set集合查詢時間復(fù)雜度為o(1))
代碼
C++
class Solution {
public:
int robotSim(vector<int>& commands, vector<vector<int>>& obstacles) {
int dirs[4][2] = {{-1, 0}, {0, 1}, {1, 0}, {0, -1}};
int sx = 0, sy = 0, res = 0, d = 1;
set<pair<int, int>> mp;
for(int i = 0; i < obstacles.size(); ++i){
pair<int, 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];
pair<int, 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, 0
d = 1
res = 0
mp = set([tuple(i) for i in obstacles])
for c in commands:
if c < 0:
d += 1 if c == -1 else -1
d %= 4
else:
for i in range(c):
if tuple([sx + dirs[d][0], sy + dirs[d][1]]) in mp:
break
else:
sx += dirs[d][0]
sy += dirs[d][1]
res = max(res, sx*sx + sy * sy)
return res
文章來源:http://www.zghlxwxcb.cn/news/detail-642858.html
到了這里,關(guān)于每日一題(set集合)-874. 模擬行走機器人的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!