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