-
Notifications
You must be signed in to change notification settings - Fork 0
/
Snake and ladder using BFS-SSSP algo.cpp
148 lines (121 loc) · 2.82 KB
/
Snake and ladder using BFS-SSSP algo.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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
#include<iostream>
#include<list>
#include<queue>
using namespace std;
class Graph{
int V;
list<int> *l;
public:
Graph(int v){
V = v;
l = new list<int>[V];
}
void addEdge(int u,int v,bool bidir=true){
l[u].push_back(v);
if(bidir){
l[v].push_back(u);
}
}
void printAdjList(){
for(int i=0;i<V;i++){
cout<<i<<"->";
for(int node:l[i]){
cout<<node<<",";
}
cout<<endl;
}
}
void bfs(int src){
queue<int> q;
int *dist = new int[V];
for(int i=0;i<V;i++){
dist[i] = INT_MAX;
}
///Algorithm
dist[src] = 0;
q.push(src);
while(!q.empty()){
int node = q.front();
cout<<node<<" ";
q.pop();
for(int child : l[node]){
if(dist[child]==INT_MAX){
dist[child] = dist[node] + 1;
q.push(child);
}
}
}
///Print Src to All Node Distances
for(int i=0;i<V;i++){
cout<<"Dist of "<<i<<" is "<<dist[i]<<endl;
}
}
void bfsPath(int src,int dest){
queue<int> q;
int *dist = new int[V];
int *parent = new int[V];
for(int i=0;i<V;i++){
dist[i] = INT_MAX;
parent[i] = -1;
}
///Algorithm
dist[src] = 0;
q.push(src);
while(!q.empty()){
int node = q.front();
//cout<<node<<" ";
q.pop();
for(int child : l[node]){
if(dist[child]==INT_MAX){
dist[child] = dist[node] + 1;
parent[child] = node;
q.push(child);
}
}
}
///Print Src to All Node Distances
int currentNode = dest;
while(currentNode!=-1){
cout<<currentNode<<"<--";
currentNode = parent[currentNode];
}
}
};
int main(){
Graph g(7);
g.addEdge(1,0);
g.addEdge(1,2);
g.addEdge(3,2);
g.addEdge(3,6);
g.addEdge(6,0);
g.addEdge(3,5);
g.addEdge(4,5);
g.addEdge(2,4);
//g.printAdjList();
//g.bfs(1);
//g.bfsPath(1,5);
cout<<endl;
//g.bfsPath(5,1);
int board[50] = {0};
board[2]= 13;
board[5] = 2;
board[9] = 18;
board[18] = 11;
board[17] = -13;
board[20] = -14;
board[24] = -8;
board[25] = 10;
board[32] = -2;
board[34] = -22;
Graph game(37);
for(int u=0;u<36;u++){
for(int dice=1;dice<=6;dice++){
int v = u + dice + board[u+dice];
if(v<=36){
game.addEdge(u,v,false);
}
}
}
game.bfsPath(0,36);
return 0;
}