有向图的欧拉路径

 1 class Solution 
 2 {
 3 public:
 4     //欧拉路径
 5     vector<string> findItinerary(vector<vector<string>> &tickets) 
 6     {
 7         unordered_map<string, multiset<string>> from_to;//multiset相当于小根堆
 8         for (auto ticket:tickets) from_to[ticket[0]].insert(ticket[1]);
 9         vector<string> ans;
10         dfs("JFK", from_to, ans);
11         return vector<string>(ans.rbegin(), ans.rend());
12     }
13 
14     //有向图的欧拉路径
15     void dfs(string from, unordered_map<string, multiset<string>> &from_to, vector<string> &ans) 
16     {
17         while (!from_to[from].empty()) 
18         {
19             string next = *from_to[from].begin();
20             from_to[from].erase(from_to[from].begin());//可能存在相同的地点,所以只能erase迭代器
21             dfs(next, from_to, ans);
22         }
23         ans.push_back(from);//一定倒着存,将孤立节点放在最后访问。题目保证一定会有路径
24     }
25 };

猜你喜欢

转载自www.cnblogs.com/yuhong1103/p/12750159.html