1106D. Lunar New Year and a Wander - Codeforces Solution C++

  Problem Link : 1106D. Lunar New Year and a Wander 


✅ C++ Solution :

 
#include<bits/stdc++.h>
using namespace std;

#define ll long long int



int main()
{
	int n,m;
	cin>>n>>m;

	vector<int> adj[n+1];
	bool visited[n+1];

	for(int i=0;i<=n;i++)
	{
		adj[i].clear();
		visited[i]=0;
	}

	int u,v;
	while(m--)
	{
		cin>>u>>v;
		adj[u].push_back(v);
		adj[v].push_back(u);
	}

	priority_queue<int,vector<int>,greater<int>> pq;
	pq.push(1);
	visited[1]=1;
	while(!pq.empty())
	{
		v=pq.top();
		pq.pop();
		cout<<v<<" ";
		for(int i=0;i<adj[v].size();i++)
		{
			if(!visited[adj[v][i]])
			{
				visited[adj[v][i]]=1;
				pq.push(adj[v][i]);
			}
		}
	}



}

 

Thank you for your patience reading. If you enjoyed this post, I’d be very grateful if you’d help it spread by emailing it to a friend, or sharing it on Whatsapp or Facebook. 

😇Happy Learning!!