Print the lexicographically smallest BFS of the graph starting from 1
Given a connected graph with N vertices and M edges. The task is to print the lexicographically smallest BFS traversal of the graph starting from 1.
Note: The vertices are numbered from 1 to N.
Examples:
Input: N = 5, M = 5
Edges:
1 4
3 4
5 4
3 2
1 5
Output: 1 4 3 2 5
Start from 1, go to 4, then to 3 and then to 2 and to 5.
Input: N = 3, M = 2
Edges:
1 2
1 3
Output: 1 2 3
Approach: Instead of doing a normal BFS traversal on the graph, we can use a priority queue(min-heap) instead of a simple queue. When a node is visited add its adjacent nodes into the priority queue. Every time, we visit a new node, it will be the one with the smallest index in the priority queue. Print the nodes when every time we visit them starting from 1.
Below is the implementation of the above approach:
CPP
#include <bits/stdc++.h>
using namespace std;
void printLexoSmall(vector< int > adj[], int n)
{
bool vis[n + 1];
memset (vis, 0, sizeof vis);
priority_queue< int , vector< int >, greater< int > > Q;
vis[1] = true ;
Q.push(1);
while (!Q.empty()) {
int now = Q.top();
Q.pop();
cout << now << " " ;
for ( auto p : adj[now]) {
if (!vis[p]) {
Q.push(p);
vis[p] = true ;
}
}
}
}
void insertEdges( int u, int v, vector< int > adj[])
{
adj[u].push_back(v);
adj[v].push_back(u);
}
int main()
{
int n = 5, m = 5;
vector< int > adj[n + 1];
insertEdges(1, 4, adj);
insertEdges(3, 4, adj);
insertEdges(5, 4, adj);
insertEdges(3, 2, adj);
insertEdges(1, 5, adj);
printLexoSmall(adj, n);
return 0;
}
|
Java
import java.util.*;
public class GFG
{
static void printLexoSmall(Vector<Vector<Integer>> adj, int n)
{
boolean [] vis = new boolean [n + 1 ];
Vector<Integer> Q = new Vector<Integer>();
vis[ 1 ] = true ;
Q.add( 1 );
while (Q.size() > 0 ) {
int now = Q.get( 0 );
Q.remove( 0 );
System.out.print(now + " " );
for ( int p : adj.get(now)) {
if (!vis[p]) {
Q.add(p);
Collections.sort(Q);
vis[p] = true ;
}
}
}
}
static void insertEdges( int u, int v, Vector<Vector<Integer>> adj)
{
adj.get(u).add(v);
adj.get(v).add(u);
}
public static void main(String[] args) {
int n = 5 ;
Vector<Vector<Integer>> adj = new Vector<Vector<Integer>>();
for ( int i = 0 ; i < n + 1 ; i++)
{
adj.add( new Vector<Integer>());
}
insertEdges( 1 , 4 , adj);
insertEdges( 3 , 4 , adj);
insertEdges( 5 , 4 , adj);
insertEdges( 3 , 2 , adj);
insertEdges( 1 , 5 , adj);
printLexoSmall(adj, n);
}
}
|
Python3
def printLexoSmall(adj, n):
vis = [ False for i in range (n + 1 )]
Q = []
vis[ 1 ] = True ;
Q.append( 1 )
while ( len (Q) ! = 0 ):
now = Q[ 0 ]
Q.pop( 0 )
print (now, end = " " )
for p in adj[now]:
if ( not vis[p]):
Q.append(p)
Q.sort()
vis[p] = True
def insertEdges(u, v, adj):
adj[u].append(v)
adj[v].append(u)
n = 5
m = 5
adj = [[] for i in range (n + 1 )]
insertEdges( 1 , 4 , adj)
insertEdges( 3 , 4 , adj)
insertEdges( 5 , 4 , adj)
insertEdges( 3 , 2 , adj)
insertEdges( 1 , 5 , adj)
printLexoSmall(adj, n)
|
C#
using System;
using System.Collections.Generic;
class GFG {
static void printLexoSmall(List<List< int >> adj, int n)
{
bool [] vis = new bool [n + 1];
List< int > Q = new List< int >();
vis[1] = true ;
Q.Add(1);
while (Q.Count > 0) {
int now = Q[0];
Q.RemoveAt(0);
Console.Write(now + " " );
foreach ( int p in adj[now]) {
if (!vis[p]) {
Q.Add(p);
Q.Sort();
vis[p] = true ;
}
}
}
}
static void insertEdges( int u, int v, List<List< int >> adj)
{
adj[u].Add(v);
adj[v].Add(u);
}
static void Main()
{
int n = 5;
List<List< int >> adj = new List<List< int >>();
for ( int i = 0; i < n + 1; i++)
{
adj.Add( new List< int >());
}
insertEdges(1, 4, adj);
insertEdges(3, 4, adj);
insertEdges(5, 4, adj);
insertEdges(3, 2, adj);
insertEdges(1, 5, adj);
printLexoSmall(adj, n);
}
}
|
Javascript
<script>
function printLexoSmall(adj,n)
{
let vis = new Array(n + 1);
for (let i=0;i<n+1;i++)
{
vis[i]= false ;
}
let Q = [];
vis[1] = true ;
Q.push(1);
while (Q.length > 0) {
let now = Q[0];
Q.shift();
document.write(now + " " );
for (let p=0;p< adj[now].length;p++) {
if (!vis[adj[now][p]]) {
Q.push(adj[now][p]);
Q.sort( function (a,b){ return a-b;});
vis[adj[now][p]] = true ;
}
}
}
}
function insertEdges(u,v,adj)
{
adj[u].push(v);
adj[v].push(u);
}
n = 5;
let adj = [];
for (let i = 0; i < n + 1; i++)
{
adj.push([]);
}
insertEdges(1, 4, adj);
insertEdges(3, 4, adj);
insertEdges(5, 4, adj);
insertEdges(3, 2, adj);
insertEdges(1, 5, adj);
printLexoSmall(adj, n);
</script>
|
Time Complexity: O(N*logN), as we are using a loop to traverse N times and in each traversal, we are doing a priority queue operation which will cost logN time. Where N is the total number of nodes in the tree.
Auxiliary Space: O(N), as we are using extra space for vis and priority queue.
Last Updated :
16 Jun, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...