single shortest path using bfs

PHOTO EMBED

Mon Jan 10 2022 06:58:31 GMT+0000 (Coordinated Universal Time)

Saved by @vaibhav_55

          vector g[100001];
          vector visi(100001,0);

            //finding the single source shortest path using bfs
void bfs(ll v, ll n)
{

	vector dist(10001);
	queue q;

	q.push(v);
	visi[v] = 1;
	dist[v] = 0;
	ll level = 1;

	while (!q.empty()) {
		ll node = q.front();
		q.pop();
		cout  << node << " ";

		ll n = q.size();
		for (int i = 0; i < n; i++) {
			cout << "level " << level << endl;

		}

		for (ll child : g[node]) {
			if (visi[child] == 0) {
				dist[child] = 1 + dist[node];
				q.push(child);
				visi[child] = 1;
			}
		}

	}

	cout << "\nNodes and their corresponding distance" << endl;

	for (int i = 1; i <= n; i++)
		cout << i << "-->" << dist[i] << endl;

}
          
      
content_copyCOPY

Unlike,dfs this can be used to find the shortest path from single point to any other point,but graph must be unweighted.