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

首頁 > 學院 > 開發設計 > 正文

[LeetCode] Reconstruct Itinerary

2019-11-09 17:26:45
字體:
來源:轉載
供稿:網友

題目

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。 對于路徑中的其它點,只能和路徑組成環,在dfs遞歸回退的過程中,每一點繼續dfs遍歷,最終會阻塞在L上,并組成一個環,回退該路徑并記錄即可。相當于在每個點尋找到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); }}
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 高平市| 察哈| 资溪县| 泰来县| 巴青县| 百色市| 静海县| 嘉兴市| 常州市| 内黄县| 安西县| 蒙城县| 九龙坡区| 张家口市| 揭东县| 蓝田县| 乐业县| 尤溪县| 甘南县| 蚌埠市| 南木林县| 青海省| 黔江区| 萍乡市| 湛江市| 新密市| 新化县| 厦门市| 扎鲁特旗| 昭觉县| 宁阳县| 呈贡县| 白银市| 宜兰市| 溧阳市| 姜堰市| 靖江市| 大理市| 万盛区| 汪清县| 德惠市|