Re: [閒聊] 每日leetcode

作者: oin1104 (是oin的說)   2024-09-04 12:26:58
※ 引述 《enmeitiryous (enmeitiryous)》 之銘言:
:  
: 題目: 874 walking robot simulation
: 一個機器人起始在(0,0)並面向+y的方向,給你一串指令 commands,當coomands[i]=-1代
: 表向右轉,-2代表向左轉,否則代表朝面向方向走的距離,給你一個blockers座標vector
: 如果機器人的下一步存在該列表中則機器人原地停下,求在過程中最大的x**2+y**2
:  
思路:
讓一個人去走
一個是jiwp的人的oin去走
我是jiwp的人...
記錄方向
然後遇到牆壁就停下來
怎麼紀錄牆壁的話
我想用unordered set
因為比較快
雖然後面發現set就可以了 幹
然後這就是這題麻煩的地方了
因為unordered set
不支援pair <int, int>的hash value
這代表什麼
https://i.imgur.com/ivcHGPa.png
反正就是沒辦法用
因為它只支援基礎的int string 之類的
pair的hash 值沒有被定義
那麼
我們就必須幫他做出來
所以去查一下怎麼做之後
就可以寫出來了
```cpp
typedef struct jiwp{
int dir_[4][2];
int dir;
int x;
int y;
jiwp(){
dir_[0][0] = 1;
dir_[0][1] = 0;
dir_[1][0] = 0;
dir_[1][1] = -1;
dir_[2][0] = -1;
dir_[2][1] = 0;
dir_[3][0] = 0;
dir_[3][1] = 1;
}
}jiwp ;
struct pair_hash {

template <class T1, class T2>
size_t operator() (const pair<T1, T2>& p) const {
auto h1 = hash<T1>{}(p.first);
auto h2 = hash<T2>{}(p.second);
return h1 ^ h2;
}
};
class Solution {
public:
int robotSim(vector<int>& commands, vector<vector<int>>& obstacles)
{
jiwp oin;
oin.dir = 3;
oin.x = 0;
oin.y = 0;
int res = 0;
unordered_set<pair<int, int>, pair_hash> paper;
for(auto k : obstacles)
{
paper.insert({k[0],k[1]});
}
for(int i : commands)
{
if(i < 0)
{
if(i==-1)
{
oin.dir = (oin.dir+1)%4;
}
else if(i==-2)
{
oin.dir = (oin.dir+3)%4;
}
continue;
}
for(int j = 0 ; j < i ; j ++)
{
int next_x = oin.x + oin.dir_[oin.dir][0] ;
int next_y = oin.y + oin.dir_[oin.dir][1] ;
if(paper.find({next_x , next_y}) == paper.end())
{
oin.x = next_x;
oin.y = next_y;
}
}
res = max(res , oin.x*oin.x + oin.y*oin.y);
}
return res;
}
};
```

Links booklink

Contact Us: admin [ a t ] ucptt.com