The Wayback Machine - https://web.archive.org/web/20240707211151/https://www.geeksforgeeks.org/traverse-graph-in-lexicographical-order-of-nodes-using-dfs/
Open In App

Traverse graph in lexicographical order of nodes using DFS

Last Updated : 15 Mar, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given a graph, G consisting of N nodes, a source S, and an array Edges[][2] of type {u, v} that denotes that there is an undirected edge between node u and v, the task is to traverse the graph in lexicographical order using DFS.

Examples:

Input: N = 10, M = 10, S = ‘a’, Edges[][2] = { { ‘a’, ‘y’ }, { ‘a’, ‘z’ }, { ‘a’, ‘p’ }, { ‘p’, ‘c’ }, { ‘p’, ‘b’ }, { ‘y’, ‘m’ }, { ‘y’, ‘l’ }, { ‘z’, ‘h’ }, { ‘z’, ‘g’ }, { ‘z’, ‘i’ } } 
Output: a p b c y l m z g h i

Explanation: 
For the first level visit the node and print it: 
 

Similarly visited the second level node p which is lexicographical smallest as: 
 

Similarly visited the third level for node p in lexicographical order as: 
 

Now the final traversal is shown in the below image and labelled as increasing order of number: 
 

 

Input: N = 6, S = ‘a’, Edges[][2] = { { ‘a’, ‘e’ }, { ‘a’, ‘d’ }, { ‘e’, ‘b’ }, { ‘e’, ‘c’ }, { ‘d’, ‘f’ }, { ‘d’, ‘g’ } } 
Output: a d f g e b c

 

Approach: Follow the steps below to solve the problem:

  • Initialize a map, say G to store all the adjacent nodes of a node according to lexicographical order of the nodes.
  • Initialize a map, say vis to check if a node is already traversed or not.
  • Traverse the Edges[][2] array and store all the adjacent nodes of each node of the graph in G.
  • Finally, traverse the graph using DFS and print the visited nodes of the graph.

Below is the implementation of the above approach:

C++




// C++ program  for the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to traverse the graph in
// lexicographical order using DFS
void LexiDFS(map<char, set<char> >& G,
             char S, map<char, bool>& vis)
{
    // Mark S as visited nodes
    vis[S] = true;
 
    // Print value of visited nodes
    cout << S << " ";
 
    // Traverse all adjacent nodes of S
    for (auto i = G[S].begin();
         i != G[S].end(); i++) {
 
        // If i is not visited
        if (!vis[*i]) {
 
            // Traverse all the nodes
            // which is connected to i
            LexiDFS(G, *i, vis);
        }
    }
}
 
// Utility Function to traverse graph
// in lexicographical order of nodes
void CreateGraph(int N, int M, int S,
                 char Edges[][2])
{
    // Store all the adjacent nodes
    // of each node of a graph
    map<char, set<char> > G;
 
    // Traverse Edges[][2] array
    for (int i = 0; i < M; i++) {
 
        // Add the edges
        G[Edges[i][0]].insert(
            Edges[i][1]);
    }
 
    // Check if a node is already
    // visited or not
    map<char, bool> vis;
 
    // Function Call
    LexiDFS(G, S, vis);
}
 
// Driver Code
int main()
{
    int N = 10, M = 10, S = 'a';
    char Edges[M][2]
        = { { '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);
 
    return 0;
}


Java




// Java program for above approach
import java.util.*;
 
class Graph{
 
// Function to traverse the graph in
// lexicographical order using DFS
static void LexiDFS(HashMap<Character, Set<Character>> G,
            char S, HashMap<Character, Boolean> vis)
{
     
    // Mark S as visited nodes
    vis.put(S, true);
 
    // Print value of visited nodes
    System.out.print(S + " ");
 
    // Traverse all adjacent nodes of S
    if (G.containsKey(S))
    {
        for(char i : G.get(S))
        {
             
            // If i is not visited
            if (!vis.containsKey(i) || !vis.get(i))
            {
                 
                // Traverse all the nodes
                // which is connected to i
                LexiDFS(G, i, vis);
            }
        }
    }
}
 
// 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
    HashMap<Character, Set<Character>> G = new HashMap<>();
 
    // Traverse Edges[][2] array
    for(int i = 0; i < M; i++)
    {
        if (G.containsKey(Edges[i][0]))
        {
            Set<Character> temp = G.get(Edges[i][0]);
            temp.add(Edges[i][1]);
            G.put(Edges[i][0], temp);
        }
        else
        {
            Set<Character> temp = new HashSet<>();
            temp.add(Edges[i][1]);
            G.put(Edges[i][0], temp);
        }
    }
     
    // Check if a node is already visited or not
    HashMap<Character, Boolean> vis = new HashMap<>();
 
    LexiDFS(G, S, vis);
}
 
// Driver code
public static void main(String[] args)
{
    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 hritikrommie


Python3




# Python3 program  for the above approach
G = [[] for i in range(300)]
vis = [0 for i in range(300)]
 
# Function to traverse the graph in
# lexicographical order using DFS
def LexiDFS(S):
    global G, vis
     
    # Mark S as visited nodes
    vis[ord(S)] = 1
 
    # Prvalue of visited nodes
    print (S,end=" ")
 
    # Traverse all adjacent nodes of S
    for i in G[ord(S)]:
        # If i is not visited
        if (not vis[i]):
            # Traverse all the nodes
            # which is connected to i
            LexiDFS(chr(i))
 
# Utility Function to traverse graph
# in lexicographical order of nodes
def CreateGraph(N, M, S, Edges):
    global G
    # Store all the adjacent nodes
    # of each node of a graph
 
    # Traverse Edges[][2] array
    for i in Edges:
        # Add the edges
        G[ord(i[0])].append(ord(i[1]))
        G[ord(i[0])] = sorted(G[ord(i[0])])
 
    # Function Call
    LexiDFS(S)
 
# Driver Code
if __name__ == '__main__':
    N = 10
    M = 10
    S = 'a'
    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 mohitkumar29.


Javascript




<script>
 
// JavaScript program  for the above approach
 
let G = new Array(300).fill(0).map(() => [])
let vis = new Array(300).fill(0)
 
// Function to traverse the graph in
// lexicographical order using DFS
function LexiDFS(S) {
    // Mark S as visited nodes
    vis[S.charCodeAt(0)] = 1
 
    // Prvalue of visited nodes
    document.write(S + " ")
 
    // Traverse all adjacent nodes of S
    for (let i of G[S.charCodeAt(0)]) {
        // If i is not visited
        if (!vis[i]) {
            // Traverse all the nodes
            // which is connected to i
            LexiDFS(String.fromCharCode(i))
        }
    }
}
 
// Utility Function to traverse graph
// in lexicographical order of nodes
function CreateGraph(N, M, S, Edges) {
    // Store all the adjacent nodes
    // of each node of a graph
 
    // Traverse Edges[][2] array
    for (let i of Edges) {
        // Add the edges
        G[i[0].charCodeAt(0)].push(i[1].charCodeAt(0))
         
        G[i[0].charCodeAt(0)] =
        G[i[0].charCodeAt(0)].sort((a, b) => a - b)
    }
 
    // Function Call
    LexiDFS(S)
}
 
// Driver Code
let N = 10
let M = 10
let S = 'a'
let 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 _saurabh_jaiswal
 
</script>


C#




// C# program  for the above approach
using System;
using System.Collections.Generic;
 
class Graph {
    // Function to traverse the graph in
    // lexicographical order using DFS
    static void LexiDFS(List<int>[] G, int S, bool[] vis) {
        // Mark S as visited nodes
        vis[S] = true;
 
        // Print value of visited nodes
        Console.Write(Convert.ToChar(S) + " ");
 
        // Traverse all adjacent nodes of S
        foreach (int i in G[S]) {
            // If i is not visited
            if (!vis[i]) {
                // Traverse all the nodes
                // which is connected to i
                LexiDFS(G, i, vis);
            }
        }
    }
 
    // 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
        List<int>[] G = new List<int>[300];
        for (int i = 0; i < G.Length; i++) {
            G[i] = new List<int>();
        }
 
        // Traverse Edges[][2] array
        for (int i = 0; i < M; i++) {
            // Add the edges
            G[Edges[i][0]].Add(Edges[i][1]);
 
            G[Edges[i][0]].Sort();
        }
 
        // Check if a node is already visited or not
        bool[] vis = new bool[300];
 
        LexiDFS(G, S, vis);
    }
 
    // Driver code
    static void Main(string[] args) {
        int N = 10;
        int M = 10;
        char S = 'a';
 
        char[][] Edges = {
            new char[] { 'a', 'y' },
            new char[] { 'a', 'z' },
            new char[] { 'a', 'p' },
            new char[] { 'p', 'c' },
            new char[] { 'p', 'b' },
            new char[] { 'y', 'm' },
            new char[] { 'y', 'l' },
            new char[] { 'z', 'h' },
            new char[] { 'z', 'g' },
            new char[] { 'z', 'i' }
        };
 
        // Function Call
        CreateGraph(N, M, S, Edges);
    }
}
 
// This code is contributed by Jay


Output: 

a p b c y l m z g h i

 

Time Complexity: O(N * log(N)) 
Auxiliary Space: O(N)



Similar Reads

Traversal of a Graph in lexicographical order using BFS
C/C++ Code // C++ program to implement // the above approach #include &lt;bits/stdc++.h&gt; using namespace std; // Function to traverse the graph in // lexicographical order using BFS void LexiBFS(map&lt;char, set&lt;char&gt; &gt;&amp; G, char S, map&lt;char, bool&gt;&amp; vis) { // Stores nodes of the graph // at each level queue&lt;char&gt; q; /
9 min read
Calculate number of nodes between two vertices in an acyclic Graph by DFS method
Given a connected acyclic graph consisting of V vertices and E edges, a source vertex src, and a destination vertex dest, the task is to count the number of vertices between the given source and destination vertex in the graph. Examples: Input: V = 8, E = 7, src = 7, dest = 8, edges[][] ={{1 4}, {4, 5}, {4, 2}, {2, 6}, {6, 3}, {2, 7}, {3, 8}}Output
10 min read
Find a set of at most N/2 nodes from a Graph such that all remaining nodes are directly connected to one of the chosen nodes
Given an integer N, representing the number of nodes present in an undirected graph, with each node valued from 1 to N, and a 2D array Edges[][], representing the pair of vertices connected by an edge, the task is to find a set of at most N/2 nodes such that nodes that are not present in the set, are connected adjacent to any one of the nodes prese
12 min read
Traverse Linked List from middle to left-right order using recursion
Given a Linked List. The task is to traverse the Linked List from middle to left-right order using recursion.For Example: If the given Linked List is: 2 -&gt; 5 -&gt; 8 -&gt; 3 -&gt; 7 -&gt; 9 -&gt; 12 -&gt; NULL The Middle to left-right order is : 3, 8, 7, 5, 9, 2, 12 Explanation: Middle of the given linked list is '3' so, we start traversing from
15+ min read
Generate all the numbers up to N in Lexicographical Order using Stack
Given an integer N, the task is to print all numbers up to N in Lexicographical order. Examples: Input: N = 20Output: 1 10 11 12 13 14 15 16 17 18 19 2 3 4 5 6 7 8 9 Input: N = 5Output: 1 2 3 4 Input: N = 19 Output: 1 10 11 12 13 14 15 16 17 18 2 3 4 5 6 7 8 9 Approach: In order to solve the problem, follow the steps below: Initialize two stacks st
7 min read
Shortest path to traverse all the elements of a circular array in increasing order
There are N distinct integers arranged on a circle. The distance between any two adjacent numbers is 1. The task is to travel on this circle starting with the smallest number, then moving to the second smallest, third smallest, and so on until the largest number and print the minimum travel distance. Examples: Input: arr[] = {3, 6, 5, 1, 2, 4} Outp
6 min read
Sort the words in lexicographical order in Python
Given a strings, we need to sort the words in lexicographical order (dictionary order). Examples : Input : "hello python program how are you" Output : are hello how program python you Input : "Coders loves the algorithms" Output : Coders algorithms loves the Note: The words which have first letter is capital letter they will print according alphabe
2 min read
Print all distinct circular strings of length M in lexicographical order
Given a string and an integer M, print all distinct circular strings of length M in lexicographical order. Examples: Input: str = "baaaa", M = 3 Output: aaa aab aba baa All possible circular substrings of length 3 are "baa" "aaa" "aaa" "aab" "aba" Out of the 6, 4 are distinct, and the lexicographical order is aaa aab aba baa Input: str = "saurav",
5 min read
Print all the combinations of a string in lexicographical order
Given a string str, print of all the combinations of a string in lexicographical order.Examples: Input: str = "ABC" Output: A AB ABC AC ACB B BA BAC BC BCA C CA CAB CB CBA Input: ED Output: D DE E ED Approach: Count the occurrences of all the characters in the string using a map, then using recursion all the possible combinations can be printed. St
9 min read
Find the k-th string in lexicographical order consisting of n-2 X's and 2 Y's
Given two numbers N and K, the task is to find the Kth string in lexicographical order if the starting string contains (N-2) x's first and then 2 Y'sNote: 1 ? K ? N*(N-1)/2, N*(N-1)/2 are the number of possible permutations Examples: Input : N = 5, K = 7 Output : YXXXY The possible strings in lexicographical order 1. XXXYY 2. XXYXY 3. XXYYX 4. XYXX
6 min read
Practice Tags :
three90RightbarBannerImg