shortest path algorithm with unit weight
//Shortest Path in Undirected graph using Unit weight BFS
//Check the striver graph series
#include<bits/stdc++.h>
using namespace std;
void addedge(vector<int>adj[],int u,int v)
{
adj[u].push_back(v);
adj[v].push_back(u);
}
void shortest(vector<int>adj[],int n , int source)
{
int distance[n];
for(int i=0;i<n;i++)
{
distance[i]=INT_MAX;
}
queue<int>q;
distance[source]=0;
q.push(source);
while(!q.empty())
{
int node=q.front();
q.pop();
for(auto j:adj[node])
{
if(distance[node]+1<distance[j])
{
distance[j]=distance[node]+1;
q.push(j);
}
}
}
for(int i=0;i<n;i++)
{
cout<<distance[i]<<" ";
}
}
int main()
{
int vertex,edges;
cout<<"Enter the number of vertex and edges:"<<endl;
cin>>vertex>>edges;
vector<int>adj[vertex];
int a,b;
cout<<"Enter the links:"<<endl;
for(int i=0;i<edges;i++)
{
cin>>a>>b;
addedge(adj,a,b);
}
int value;
cout<<"Enter the node from which you want to calculate the shortest distance:"<<endl;
cin>>value;
shortest(adj,vertex,value);
return 0;
}