Created
April 4, 2022 05:18
-
-
Save devil-cyber/f7396c3a9f4c38c1ef6552a119c08eaa to your computer and use it in GitHub Desktop.
Shortest Pth Uisng Bfs in Graph
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include<iostream> | |
#include<vector> | |
#include<queue> | |
using namespace std; | |
class Graph{ | |
int V; | |
vector<int> *l; | |
public: | |
Graph(int v){ | |
V = v; | |
l = new vector<int>[V]; | |
} | |
void addEdge(int x, int y, bool undir=true){ | |
l[x].push_back(y); | |
if(undir) | |
l[y].push_back(x); | |
} | |
void bfs(int src, int v, int dest=-1){ | |
queue<int> q; | |
vector<bool> visted(v, false); | |
vector<int> parent(v, 0); | |
q.push(src); | |
parent[src] = src; | |
while(!q.empty()){ | |
int val = q.front(); | |
q.pop(); | |
for(auto node : l[val]){ | |
if(!visted[node]){ | |
visted[node]=true; | |
q.push(node); | |
parent[node] = val; | |
} | |
} | |
} | |
if(dest!=-1){ | |
int temp = dest; | |
while(temp!=src){ | |
cout<<temp<<" "; | |
temp = parent[temp]; | |
} | |
cout<<src<<" "; | |
cout<<endl; | |
} | |
} | |
}; | |
int main(){ | |
Graph g(6); | |
g.addEdge(0, 1); | |
g.addEdge(1, 2); | |
g.addEdge(2, 4); | |
g.addEdge(4, 5); | |
g.addEdge(0, 3); | |
g.addEdge(3, 5); | |
g.bfs(0, 5, 5); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment