Given a sorted dictionary (array of words) of an alien language, find order of characters in the language.

0

 Given a sorted dictionary (array of words) of an alien language, find order of characters in the language.




Cpp Program Code:



The build_graph function takes a vector of strings words, an empty unordered_map graph, and an empty unordered_set chars as input. It first initializes the chars set with all the unique characters in the words, and then initializes the graph with empty sets for each character.


The function then iterates through the words and adds directed edges between nodes based on the dictionary order. For each adjacent pair of words, the function compares the characters at each position until it finds the first position where they differ. It then adds a directed edge from the character in the first word to the character in the second word at that position.


The topological_sort function performs a recursive depth-first search on the graph starting at the node c, and adds the visited nodes to a visited set and a queue order in reverse topological order.


Finally, the main function calls build_graph to build the graph, and then iterates through all the characters in the chars set, calling topological_sort on each unvisited node. The resulting queue order is then printed to


Python Program code:




In this code, we first define a function addEdge to add a directed edge to the graph. We then define a function buildGraph to build the graph by comparing adjacent words in the sorted dictionary. The function topologicalSort performs the topological sort on the graph, and the function findOrder puts everything together and prints the order of characters in the alien language.


Post a Comment

0Comments
Post a Comment (0)