-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSnakeLadderMinThrow.cpp
More file actions
71 lines (61 loc) · 1.86 KB
/
SnakeLadderMinThrow.cpp
File metadata and controls
71 lines (61 loc) · 1.86 KB
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
// { Driver Code Starts
// Initial Template for C++
#include <bits/stdc++.h>
using namespace std;
// } Driver Code Ends
// User function Template for C++
class Solution {
public:
int bfs(unordered_map<int, int> snake, unordered_map<int, int> ladder, int n) {
queue<pair<int, int>> que;
que.push({1, 0});
while (!que.empty()) {
int pos = que.front().first;
int num = que.front().second;
que.pop();
cout << pos << endl;
if (pos == 30) {
return num;
}
for (int i = 1; i <= 6; i++) {
auto itSnake = snake.find(pos + i);
auto itLadder = ladder.find(pos + i);
if (itLadder != ladder.end()) {
que.push({(*itLadder).second, num + 1});
} else if (itSnake != snake.end()) {
que.push({(*itSnake).second, num + 1});
} else {
que.push({pos + i, num + 1});
}
}
}
}
int minThrow(int N, int arr[]) {
int ans = 0;
unordered_map<int, int> snake, ladder;
for (int i = 0; i < N; i += 2) {
snake.insert({arr[i], arr[(i) + 1]});
ladder.insert({arr[i + N], arr[(i) + 1 + N]});
}
// for (auto ele : snake) cout << ele.first << " " << ele.second << endl;;
// cout << endl;
// for (auto ele : ladder) cout << ele.first << " " << ele.second << endl;
ans = bfs(snake, ladder, N);
return ans;
}
};
// { Driver Code Starts.
int main() {
int t;
cin >> t;
while (t--) {
int N;
cin >> N;
int arr[2 * N];
for (int i = 0; i < 2 * N; i++)
cin >> arr[i];
Solution ob;
cout << ob.minThrow(N, arr) << "\n";
}
return 0;
} // } Driver Code Ends