CODE:
//JUST FOLLOW THE COMMENTS BESIDE THE CODE, YOU CAN EASILY RELATE CODE AND THE ALGORITHM.
#include <bits/stdc++.h>
using namespace std;
vector <int> edge[10000];//2d array that will contain the vertex and edges in coordinate //form
int level[10000]; //the distance from the source, the position value i.e level[i],’i’ in here is //vertex level[i] will contain the distance from the source
int visited[10000];
int parent[10000];
int bfs(int source)
{
cout<<“Source: “<<source<<endl;//just printing out the source
queue <int> q;//taking a queue that will temporarily contain all the vertices
q.push(source);//push source into the queue
visited = 1;//source is the first move so it is made visited,it is similar to the //coloring it to grey
level = 0;//Distance from source to source is zero
while(!q.empty())//taking while loop that will run till the queue is empty
{
int u = q.front();//taking the first element of the queue in the integer u
for(int i = 0;i<edge[u].size();i++)//for loop will run till the size of row i
{
int v = edge[u][i];//v = adjacent vertex of the u
if(!visited[v])
{
visited[v] = 1;//making v as visited
level[v] = level[u] + 1;//level is greater than that of the parents
parent[v] = u;//parent of v is u
q.push(v);//the adjacent vertex of u is pushed into the queue
}
}
q.pop();//source is poped in the first move of while loop gradually others are done
}
}
int main()
{
int n,m;//n = vertex and m = number of edges
int a,b;
cin>>n>>m;
//now we will take input of vertex using a for loop
//vertex will basically be converted into edges by
//taking the input in the vector just reversing the
//positions
for(int i = 0;i<m;i++)
{
cin>>a>>b;
edge[a].push_back(b);
edge[b].push_back(a);
}
int source;
cin>>source;
memset(visited,0,sizeof(visited));//making the vertex as unvisited(white)
bfs(source);//bfs is called using a source. U can choose anyone as source
cout<<“DISTANCES:”<<endl;
for(int i = 1;i<=n;i++)
{
cout<<“DISTANCE FROM SOURCE TO “<<i<<“: “<<level[i]<<endl;
}
cout<<“PARENTS:”<<endl;
for(int i = 2;i<=n;i++)
{
cout<<“PARENT OF “<<i<<“: “<<parent[i]<<endl;
}
}