欧拉回路,Hierholzer算法
因为我们一定可以从 JFK 出发并回到 JFK ,则 JFK 一定是图中的奇点,有奇数的 in+out degrees;
Greedy DFS, building the route backwards when retreating.
public class Solution {
public List<String> findItinerary(String[][] tickets) {
LinkedList<String> list = new LinkedList<>();
HashMap<String, PriorityQueue<String>> map = new HashMap<>();
for(String[] ticket : tickets){
if(!map.containsKey(ticket[0])) map.put(ticket[0], new PriorityQueue<String>());
map.get(ticket[0]).add(ticket[1]);
}
dfs(list, "JFK", map);
return new ArrayList<String>(list);
}
private void dfs(LinkedList<String> list, String airport, HashMap<String, PriorityQueue<String>> map){
while(map.containsKey(airport) && !map.get(airport).isEmpty()){
dfs(list, map.get(airport).poll(), map);
}
list.offerFirst(airport);
}
}
Last updated