Reconstruct Itinerary

本文介绍了一种使用递归回溯的方法来解决行程重构问题的算法。该算法通过深度优先搜索(DFS)的方式遍历所有可能的行程路径,并最终返回一条从起点出发能够访问所有地点并回到起点的路径。算法首先构建了一个图数据结构,然后从指定的起点开始进行深度优先搜索,直到找到解决方案。

c++

class Solution {
public:
    vector<string> findItinerary(vector<pair<string, string>> tickets) {
        if (tickets.empty()) return vector<string>();
        unordered_map<string, multiset<string>> graph;
        for (auto &v : tickets) {
            graph[v.first].insert(v.second);
        }
        stack<string> dfs;
        dfs.push("JFK");
        vector<string> res;
        while (!dfs.empty()){
            string cur_node = dfs.top();
            if (graph[cur_node].empty()) {
                res.push_back(cur_node);
                dfs.pop();
            }
            else {
                dfs.push(*graph[cur_node].begin());
                graph[cur_node].erase(graph[cur_node].begin());
            }
        }
        reverse(res.begin(), res.end());
        return res;
    }
};

python

class Solution(object):
    def findItinerary(self, tickets):
        """
        :type tickets: List[List[str]]
        :rtype: List[str]
        """
        if not tickets: return []
        graph = collections.defaultdict(list)
        for a, b in sorted(tickets)[::-1]:
            graph[a].append(b)

        dfs = ['JFK']
        res = []
        while dfs:
            cur_node = dfs[-1]
            if not graph[cur_node]:
                res.append(dfs.pop())
            else:
                dfs.append(graph[cur_node].pop())
        return res[::-1]

reference:
1\ https://leetcode.com/discuss/85439/short-iterative-solution-explanation-recursive-backtracking
2\ Introduction to Algorithms, Chapter 22: Graph Algorithms

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值