-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjump1.cpp
55 lines (48 loc) · 1.18 KB
/
jump1.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
//
// Created by Akhilesh Rao on 28-Feb-17.
//
#include <bits/stdc++.h>
using namespace std;
int sol(int * arr,int n){
bool visit[n];
memset(visit,false, sizeof(visit));
queue<pair<int,int> > q;
visit[0]=true;
q.push(make_pair(0,0));
while(!q.empty()){
//Assigne temp
pair<int,int> temp;
temp=q.front();
q.pop();
//Check termination Condition
if(temp.first==(n)){
return temp.second;
}
//first push
if(temp.first+arr[temp.first]<=n&&temp.first+arr[temp.first]>=0){
if(!visit[temp.first+arr[temp.first]]) {
q.push(make_pair(temp.first + arr[temp.first], temp.second + 1));
visit[temp.first + arr[temp.first]] = true;
}
}
//Second push
if(temp.first+1<=n&&!visit[temp.first+1]){
q.push(make_pair(temp.first+1,temp.second+1));
visit[temp.first+1]=true;
}
}
return -1;
}
int main(){
int t;
cin>>t;
while(t--){
int n;
cin>>n;
int arr[n];
for(int i=0;i<n;i++){
cin>>arr[i];
}
cout<<sol(arr,n)<<endl;
}
}