// C# program to implement // the above approach using System; using System.Collections.Generic; class Graph { // Function to traverse the graph in // lexicographical order using BFS static void LexiBFS(Dictionary<char, HashSet<char> > G, char S, Dictionary<char, bool> vis) { // Stores nodes of the graph // at each level Queue<char> q = new Queue<char>(); // Insert nodes of first level q.Enqueue(S); // Mark S as // visited node vis[S] = true; // Traverse all nodes of the graph while (q.Count != 0) { // Stores top node of queue char top = q.Peek(); // Print visited nodes of graph Console.Write(top + " "); // Insert all adjacent nodes // of the graph into queue if (G.ContainsKey(top)) { List<char> sortedAdjList = new List<char>(G[top]); sortedAdjList.Sort(); foreach(char i in sortedAdjList) { // If i is not visited if (vis.ContainsKey(i)) { if (!vis[i]) { // Mark i as visited node vis[i] = true; // Insert i into queue q.Enqueue(i); } } else { // Mark i as visited node vis[i] = true; // Insert i into queue q.Enqueue(i); } } } // Pop top element of the queue q.Dequeue(); } } // Utility Function to traverse graph // in lexicographical order of nodes static void CreateGraph(int N, int M, char S, char[, ] Edges) { // Store all the adjacent nodes // of each node of a graph Dictionary<char, HashSet<char> > G = new Dictionary<char, HashSet<char> >(); // Traverse Edges[][2] array for (int i = 0; i < M; i++) { char u = Edges[i, 0]; char v = Edges[i, 1]; if (G.ContainsKey(u)) { G[u].Add(v); } else { HashSet<char> temp = new HashSet<char>(); temp.Add(v); G[u] = temp; } if (!G.ContainsKey(v)) { G[v] = new HashSet<char>(); } } // Check if a node is already visited or not Dictionary<char, bool> vis = new Dictionary<char, bool>(); LexiBFS(G, S, vis); } // Driver code public static void Main() { int N = 10, M = 10; char S = 'a'; char[, ] Edges = { { 'a', 'y' }, { 'a', 'z' }, { 'a', 'p' }, { 'p', 'c' }, { 'p', 'b' }, { 'y', 'm' }, { 'y', 'l' }, { 'z', 'h' }, { 'z', 'g' }, { 'z', 'i' } }; // Function Call CreateGraph(N, M, S, Edges); } } // This code is contributed by Prajwal Kandekar