Another topological sorting problem. Note:the DFS One is like a ' post-order ' traversal.
classSolution {Unordered_map<Char, unordered_set<Char>>G; Unordered_set<Char>visited; Unordered_set<Char>Rec; Public: BOOLDfsstring& Order,CharN) {if(Rec.count (n))return false; if(Visited.count (n))return true; Visited.insert (n); Rec.insert (n); for(Auto c:g[n])if(!dfs (Order, C))return false; Rec.erase (n); Order+=N; return true; } stringTopsort (unordered_map<Char, unordered_set<Char>>&g) {stringorder; for(auto kv:g)if(!DFS (order, kv.first))return ""; Std::reverse (Order.begin (), Order.end ()); returnorder; } stringAlienorder (vector<string>&words) { if(words.size () = =1)returnWords.front (); for(inti =1; I < words.size (); i++) { stringT1 = words[i-1]; stringt2 =Words[i]; BOOLFound =false; for(intj =0; J < Max (T1.length (), t2.length ()); J + +) { if(J < T1.length () && G.count (t1[j]) = =0) G[t1[j]]= unordered_set<Char>(); if(J < T2.length () && G.count (t2[j]) = =0) G[t2[j]]= unordered_set<Char>(); if(J < T1.length () && J < T2.length () && t1[j]! = T2[j] &&!found) {G[t1[j]].insert (t2[j]); Found=true; } } } returnTopsort (g); }};
View Code
Leetcode "Alien Dictionary"