Friday, January 9, 2015

Topological sort of airports


A friend of mine presents the following problem to, given a list of airports, LAX, PHL, LGA, JFK, EWK and list of routes between them: LAX->PHL, LGA->EWK, JFK->LAX, construct the whole path to connect those airports. The route can start with any airports and end at any airports. 

Take a note the problem says the destination are unknown. so we need to sort them all. 

The key to topological sort is to do DFS, then add the visited node at the end, in that way the the nodes are sorted. 

public class Airport {
public Airport(String from) {
this.name = from;
this.destinations = new ArrayList<Airport>();
}
String name;
List<Airport> destinations;
}
public class Edge{
String from;
String to;
}
public Stack<Airport> sortAirports(List<Edge> edges){
Map<String, Airport> graph = new HashMap<String, Airport>();
buildGraph(edges, graph);
Set<String> visited = new HashSet<String>();
Stack<Airport> s = new Stack<Airport>();
for(Airport a : graph.values()){
sort(a, s, visited);
}
return s;
}
public void sort(Airport a, Stack<Airport> s, Set<String> visited){
if(visited.contains(a.name))
return;
visited.add(a.name);
for(Airport d : a.destinations){
sort(d, s, visited);
}
s.add(a); <== add the earlier visited airport at last
}

No comments:

Post a Comment