Given a directed graph with N vertices and M edges that may contain cycles, the task is to find the lexicographically smallest topological ordering of the graph if it exists otherwise print -1 (if the graph has cycles).
Lexigraphically smallest topological ordering means that if two vertices in a graph do not have any incoming edge then the vertex with the smaller number should appear first in the ordering.
For Example, in the image below many topological orderings are possible e.g 5 2 3 4 0 1, 5 0 2 4 3 1.
But the smallest ordering is 4 5 0 2 3 1.
Output: 4 5 0 2 3 1
Even though 5 4 0 2 3 1 is also a valid topological
ordering of the given graph but it is not
Approach: We will use Kahn’s algorithm for Topological Sorting with a modification. Instead of using a queue we will use a multiset to store the vertices to make sure that every time we pick a vertex it is the smallest possible of all. The overall Time complexity changes to
Below is the implementation of the above approach:
4 5 0 2 3 1
- Topological Sorting
- All Topological Sorts of a Directed Acyclic Graph
- Kahn's algorithm for Topological Sorting
- Topological Sort of a graph using departure time of vertex
- Detect cycle in Directed Graph using Topological Sort
- Find the ordering of tasks from given dependencies
- Lexicographically smallest permutation of a string with given subsequences
- Lexicographically smallest string formed by removing at most one character
- Lexicographically smallest substring with maximum occurrences containing a's and b's only
- Lexicographically Smallest Permutation of length N such that for exactly K indices, a[i] > a[i] + 1
- Form lexicographically smallest string with minimum replacements having equal number of 0s, 1s and 2s
- Print the lexicographically smallest BFS of the graph starting from 1
- Print the lexicographically smallest DFS of the graph starting from 1
- Find lexicographically smallest string in at most one swaps
- Lexicographically smallest K-length substring containing maximum number of vowels
- Lexicographically smallest string which differs from given strings at exactly K indices
- Queries to return the absolute difference between L-th smallest number and the R-th smallest number
- Lexicographically largest string formed from the characters in range L and R
- Find the lexicographically largest palindromic Subsequence of a String
- Lexicographically largest sub-sequence of the given string
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.