From 57bff86903996d92827ff381c406748ebeb83ab6 Mon Sep 17 00:00:00 2001 From: Shreya <76070994+Shreya587@users.noreply.github.com> Date: Sun, 23 Oct 2022 21:58:43 +0530 Subject: [PATCH] Created Shortest Path Using BFS --- Shortest_path_BFS.cpp | 59 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 59 insertions(+) create mode 100644 Shortest_path_BFS.cpp diff --git a/Shortest_path_BFS.cpp b/Shortest_path_BFS.cpp new file mode 100644 index 0000000..5683b41 --- /dev/null +++ b/Shortest_path_BFS.cpp @@ -0,0 +1,59 @@ +//Shortest path in undirected graph using BFS. + +#include +using namespace std; +#define ll long long + +vector adj[10005]; +ll dis[10005],vis[10005]; + +void bfs(ll src){ + + queue q; + vis[src]=1; + dis[src]=0; + q.push(src); + + while(!q.empty()){ + + int node = q.front(); + q.pop(); + + for(auto it : adj[node]){ //traversing in the adjacency list. + if(vis[it]==0){ + dis[it]=dis[node]+1; + q.push(it); + vis[it]=1; + } + } + } +} + +int main(){ + ios_base::sync_with_stdio(false); + cin.tie(0); + cout.tie(0); + + ll t; + cin>>t; + + while(t--){ + + ll n,m; //no. of nodes & vertices. + cin>>n>>m; + + for(ll i=0;i<=n;i++) adj[i].clear() , vis[i]=0; + + while(m--){ + ll a,b; + cin>>a>>b; adj[a].push_back(b); adj[b].push_back(a); + } + + bfs(1); //calling the above BFS function. + + for(ll i = 1; i <= n; i++) //printing path from source to ith node. + cout<