forked from csfx-py/hacktober2020
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbfs shortest path.cpp
97 lines (84 loc) · 1.85 KB
/
bfs shortest path.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
@imhkr
graph-implementadcylist
#include<iostream>
#include<list>
#include<queue>
using namespace std;
//Adj List Implementation for Integer Nodes
class Graph{
int V;
//Array of Linked Lists of size V, V LL's are there
list<int> *adjList;
public:
Graph(int v){
V = v;
adjList = new list<int>[V];
}
void addEdge(int u,int v,bool bidir=true){
adjList[u].push_back(v);
if(bidir){
adjList[v].push_back(u);
}
}
void printAdjList(){
for(int i=0;i<V;i++){
cout<<i<<"->";
for(int node:adjList[i]){
cout<<node<<",";
}
cout<<endl;
}
}
void bfs(int src){
//Traverse all the nodes of the graph
queue<int> q;
bool *visited = new bool[V+1]{0};
int *dist = new int[V+1]{0};
// int *parent = new int[V+1];
/*
for(int i=0;i<V;i++){
parent[i] = -1;
}
*/
q.push(src);
visited[src] = true;
while(!q.empty()){
int node = q.front();
cout<<node<<" ";
q.pop();
for(int neighbour:adjList[node]){
if(!visited[neighbour]){
q.push(neighbour);
visited[neighbour] = true;
dist[neighbour] = dist[node] + 1;
//parent[neighbour] = node;
}
}
}
cout<<endl;
//Print the distances of every node from source
for(int i=0;i<V;i++){
cout<<i<<"node having dist "<<dist[i]<<endl;
}
//cout<<"Shortest dist is "<<dist[dest]<<endl;
//cout<<"Shortest path is ";
//int temp = dest;
//while(temp!=-1){
// cout<<temp<<"<--";
// temp = parent[temp];
// }
} // }
};
int main(){
Graph g(6);
g.addEdge(0,1);
g.addEdge(1,2);
g.addEdge(0,4);
g.addEdge(2,4);
g.addEdge(3,2);
g.addEdge(2,3);
g.addEdge(3,5);
g.addEdge(3,4);
g.bfs(0);
return 0;
}