作者:mobiledu2502861417 | 来源:互联网 | 2023-10-12 19:36
题面: 题解:bfs即可,不过要注意判重,相同值的加入一次即可。代码:classSolution{public:intminJumps(vector&arr){map
题面:
题解:bfs即可,不过要注意判重,相同值的加入一次即可。
代码:
class Solution {
public:
int minJumps(vector& arr) {
map >ma;
queue >q;
int n = arr.size();
for(int i = 0;i {
ma[arr[i]].emplace_back(i);
}
q.push({0, 0});
mapmb;
while(q.size())
{
auto t = q.front();
q.pop();
int step = t.first;
int x = t.second;
if(x == n-1)return step;
if(ma.count(arr[x]))
{
for(auto i : ma[arr[x]])
{
if(!mb.count(i))
{
mb[i] = 1;
q.push({step+1,i});
}
}
ma.erase(arr[x]);
}
if(x+1 {
mb[x + 1] = 1;
q.push({step+1,x+1});
}
if(x-1>=0&&!mb.count(x-1))
{
mb[x - 1] = 1;
q.push({step+1,x-1});
}
}
return -1;
}
};