leetcode--332. Reconstruct Itinerary题解

题目

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:

  1. 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"].
  2. All airports are represented by three capital letters (IATA code).
  3. You may assume all tickets form at least one valid itinerary.
    Example 1:
Input: [["MUC", "LHR"], ["JFK", "MUC"], ["SFO", "SJC"], ["LHR", "SFO"]]
Output: ["JFK", "MUC", "LHR", "SFO", "SJC"]

Example 2:

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.

思路与解法

这道题目要求我们找到从JKF出发的一条航线使得所有机票都可以用完,题目保证有解。其实就是要求我们找到一条从JKF出发的欧拉路径,不过该欧拉路经有条件:字典序最小。
直观想法是使用dfs遍历图中所有的节点和边,找到一条满足条件的路径。存储图可以使用unordered_map<string, priority_queue<string, vector<string>, greater<string>>> graph;``unordered_map效率比map更高一些,同时使用优先队列即可得到有序的节点队列(也可以使用multiset,相比而言multiset)。
满足欧拉路的图的特性:出度和入度之和为奇的点最多只有两个,即为起点和终点。

代码实现

class Solution {
	// 定义数据结构存储图和路径
    unordered_map<string,priority_queue<string, vector<string>,greater<string>>> graph;
    vector<string>itinerary;
    // 递归函数寻找欧拉路经
    void findItinerary(string node) {
    	// 使用引用,当destinations进行增删改时,graph也会进行修改
        auto& destinations = graph[node];
        while(!destinations.empty()){
            string destination = destinations.top();
            // 删除原图中的节点,避免走重复的路
            destinations.pop();
            findItinerary(destination);
        }
        // destinations.empty()成立表示我们走到了欧拉路的终点
        itinerary.push_back(node);
    }
public:
    vector<string> findItinerary(vector<pair<string, string>> tickets) {
        for(auto ticket:tickets) {
            graph[ticket.first].push(ticket.second);
        }
        // 从JFK为起点进行dfs
        findItinerary("JFK");
        // 在dfs过程中所得到的路径为逆序,所以取逆之后再返回
        reverse(itinerary.begin(), itinerary.end());
        return itinerary;
    }
};

遇到的问题

  1. terminate called after throwing an instance of ‘std::logic_error’
    what(): basic_string::_M_construct null not valid
    解释:检查代码中是否存在将NULL赋值给string的情况

  2. reference binding to null pointer of type ‘const struct basic_string’
    引用绑定到类型为“struct basic_string”的空指针,检查代码引用赋值

猜你喜欢

转载自blog.csdn.net/liuyh73/article/details/82927485