leetcode 上机器人运动范围这题需要用到pair去记录坐标。并且还需要一个容器去标记一个结点是否访问过。
想当然的就是用了unordered_set了。
但是报错了。因为unordered_set需要要我们提供一个hash方,这个方法可以我们自己写,也可以使用boost::hash
class Solution {
public:
bool check(pair<int,int>now,int k){
int first=now.first;
int second=now.second;
int sum=0;
cout<<"first"<<first<<endl;
cout<<"second"<<second<<endl;
while(first){
sum+=first%10;
first /= 10;
}
while(second){
sum+=second%10;
second /= 10;
}
cout<<"sum"<<sum<<endl;
return sum<=k;
}
int movingCount(int m, int n, int k) {
queue<pair<int,int>> q;
unordered_set<pair<int,int>,boost::hash<pair>> visited;
q.push(pair<int,int>(0,0));
int count=1;//起点算一个
while(!q.empty()){
int len= q.size();
for(int i=0;i<len;i++){
pair<int,int> now = q.front();
q.pop();
pair<int,int> next;
next=pair<int,int>(now.first+1,now.second);
if(now.first+1<m && check(next,k) && !visited.count(next)){
q.push(next);
visited.insert(next);
count++;
}
next=pair<int,int>(now.first,now.second+1);
if(now.second+1<n && check(next,k) && !visited.count(next)){
q.push(next);
visited.insert(next);
count++;
}
}
}
return count;
}
};
但是leetcode依然会报错,因为他需要头文件力扣没有。
#include <boost/functional/hash.hpp>
那么就只能我们自己实现了。但是不可能的嘛,我们就只是写点算法,自己实现是不可能的,也不是题目的考点。
其实对于类似这种图的的visit我们可以直接使用二维数组进行标记。
class Solution {
public:
bool check(pair<int,int>now,int k){
int first=now.first;
int second=now.second;
int sum=0;
while(first){
sum+=first%10;
first /= 10;
}
while(second){
sum+=second%10;
second /= 10;
}
return sum<=k;
}
int movingCount(int m, int n, int k) {
queue<pair<int,int>> q;
// unordered_set<pair<int,int>,boost::hash<pair>> visited;
vector<vector<int> > vis(m, vector<int>(n, 0));
vis[0][0]=1;
q.push(pair<int,int>(0,0));
int count=1;//起点算一个
while(!q.empty()){
int len= q.size();
for(int i=0;i<len;i++){
pair<int,int> now = q.front();
q.pop();
pair<int,int> next;
next=pair<int,int>(now.first+1,now.second);
if(now.first+1<m && check(next,k) && !vis[now.first+1][now.second]){
q.push(next);
vis[now.first+1][now.second]=1;
// cout<<now.first+1<<","<<now.second<<endl;
count++;
}
next=pair<int,int>(now.first,now.second+1);
if(now.second+1<n && check(next,k) && !vis[now.first][now.second+1]){
q.push(next);
vis[now.first][now.second+1]=1;
// cout<<now.first<<","<<now.second+1<<endl;
count++;
}
}
}
return count;
}
};