国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學(xué)院 > 開發(fā)設(shè)計 > 正文

[LeetCode] Reconstruct Itinerary

2019-11-09 16:22:29
字體:
供稿:網(wǎng)友

題目

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: tickets = [[“MUC”, “LHR”], [“JFK”, “MUC”], [“SFO”, “SJC”], [“LHR”, “SFO”]] Return [“JFK”, “MUC”, “LHR”, “SFO”, “SJC”].

解題

題目大意是找一條路徑,可以從頭到尾的羅列出每個航站。其實就是一個有向圖,然后一筆畫畫完所有的點,按順序列出所有的點。也就是歐拉路徑的定義。 首先題目定義,必然存在一條歐拉路徑,且每個點有多個路徑按字典序排序。首先采用dfs尋找字典序最小的一條路徑,直到某點阻塞,不能通往新的點,那么這一點必然是歐拉路徑的終點。也就得到了一條從起點到終點的路徑L。 對于路徑中的其它點,只能和路徑組成環(huán),在dfs遞歸回退的過程中,每一點繼續(xù)dfs遍歷,最終會阻塞在L上,并組成一個環(huán),回退該路徑并記錄即可。相當于在每個點尋找到L的路徑,并將其并回L。同時遞推回歸的過程中,先回歸的點在路徑的后面,所以要逆著記錄進鏈表。

public class Solution { LinkedList<String> res; Map<String,PriorityQueue<String>> edges; public List<String> findItinerary(String[][] tickets) { edges = new HashMap<>(); res = new LinkedList<>(); for (String[] ticket : tickets) { if (!edges.containsKey(ticket[0])){ PriorityQueue<String> queue = new PriorityQueue<>(); queue.add(ticket[1]); edges.put(ticket[0], queue); }else { edges.get(ticket[0]).add(ticket[1]); } } dfs("JFK"); return res; } private void dfs(String cur) { while (edges.containsKey(cur) && !edges.get(cur).isEmpty()) { dfs(edges.get(cur).poll()); } res.add(0,cur); }}
發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 密云县| 昆山市| 白水县| 抚远县| 石狮市| 漳州市| 阿勒泰市| 桃源县| 仁布县| 吴旗县| 秀山| 清远市| 太仆寺旗| 华坪县| 柘荣县| 兴山县| 扶风县| 石棉县| 长沙县| 湾仔区| 广东省| 前郭尔| 湄潭县| 新安县| 伊宁市| 聂荣县| 隆安县| 元阳县| 毕节市| 远安县| 长汀县| 南皮县| 益阳市| 通河县| 高清| 清苑县| 晋宁县| 孙吴县| 武义县| 武山县| 达尔|