前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >LeetCode 0332 - Reconstruct Itinerary

LeetCode 0332 - Reconstruct Itinerary

作者头像
Reck Zhang
发布2021-08-11 11:31:44
1840
发布2021-08-11 11:31:44
举报
文章被收录于专栏:Reck Zhang

Reconstruct Itinerary

Desicription

Given a list of airline tickets represented by pairs of departure and arrival airports [from, to], reconstruct the itinerary in order. All of the tickets belong to a man who departs from JFK. Thus, the itinerary must begin with JFK.

Note:

If there are multiple valid itineraries, you should return the itinerary that has the smallest lexical order when read as a single string. For example, the itinerary [“JFK”, “LGA”] has a smaller lexical order than [“JFK”, “LGB”]. All airports are represented by three capital letters (IATA code). You may assume all tickets form at least one valid itinerary. Example 1:

代码语言:javascript
复制
Input: [["MUC", "LHR"], ["JFK", "MUC"], ["SFO", "SJC"], ["LHR", "SFO"]]
Output: ["JFK", "MUC", "LHR", "SFO", "SJC"]

Example 2:

代码语言:javascript
复制
Input: [["JFK","SFO"],["JFK","ATL"],["SFO","ATL"],["ATL","JFK"],["ATL","SFO"]]
Output: ["JFK","ATL","JFK","SFO","ATL","SFO"]
Explanation: Another possible reconstruction is ["JFK","SFO","ATL","JFK","ATL","SFO"].
             But it is larger in lexical order.

Solution

代码语言:javascript
复制
class Solution {
public:
    std::vector<std::string> findItinerary(std::vector<std::vector<std::string>>& tickets) {
        auto graph = std::map<std::string, std::multiset<std::string>>();
        for(const auto& ticket : tickets) {
            graph[ticket[0]].insert(ticket[1]);
        }
        auto res = std::vector<std::string>();
        dfs("JFK", graph, res);

        return std::vector<std::string>(res.rbegin(), res.rend());
    }

private:
    static void dfs(const std::string& current, std::map<std::string, std::multiset<std::string>>& graph, std::vector<std::string>& res) {
        while(!graph[current].empty()) {
            auto next = *graph[current].begin();
            graph[current].erase(graph[current].begin());
            dfs(next, graph, res);
        }

        res.push_back(current);
    }
};
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2019-06-01,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • Reconstruct Itinerary
    • Desicription
      • Solution
      领券
      问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档