典型的深度优先遍历:
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.PriorityQueue;
/**
* Created by fhqplzj on 16-7-21 at 下午7:02.
*/
public class Hobby {
private HashMap<String, PriorityQueue<String>> graph = new HashMap<>();
private LinkedList<String> stack = new LinkedList<>();
public static void main(String[] args) {
Hobby hobby = new Hobby();
String[][] tickets = {
{"JFK", "SFO"},
{"JFK", "ATL"},
{"SFO", "JFK"}
};
System.out.println(hobby.findItinerary(tickets));
}
public List<String> findItinerary(String[][] tickets) {
for (String[] ticket : tickets) {
graph.computeIfAbsent(ticket[0], key -> new PriorityQueue<>()).add(ticket[1]);
}
dfs("JFK");
return stack;
}
public void dfs(String src) {
while (graph.containsKey(src) && !graph.get(src).isEmpty()) {
dfs(graph.get(src).poll());
}
stack.push(src);
}
}