Share the joy
This is problem is from careerup link:
You have an vector like this
[JFK, LXA, SNA, RKJ, LXA, SNA]
each 2 group define a route. so,
JFK -> LXA
SNA -> RKJ
LXA -> SNA
Find the path from departure to destination. note: departure and destination are not known.
The final destination should be
JFK-> LXA -> SNA -> RKJ
In mycode, I use DFS for topological sorting. The advantage of it is that it won’t require the in-degree information, compared to BFS. Besides, I constructed the graph by using HashMap < String, AirNode > outgoing , instead of using self-defined graph class, which make the code easier.
- import java.util.HashMap;
- import java.util.HashSet;
- import java.util.Map;
- import java.util.Set;
- import java.util.Vector;
- public class TopogicalSorintDFS {
- public static void main(String[] args) {
- Vector airports = new Vector();
- airports.add(“JFK”);
- airports.add(“LAX”);
- airports.add(“SNA”);
- airports.add(“RKJ”);
- airports.add(“LAX”);
- airports.add(“SNA”);
- Vector result = findPath(airports);
- System.out.println(result.toString());
- }
- public static Vector findPath(Vector airports) {
- Map nodes = new HashMap();
- // construct graph
- for (int i = 0; i < airports.size(); i += 2) {
- String from = airports.get(i);
- String to = airports.get(i + 1);
- if (!nodes.containsKey(from)) {
- nodes.put(from, new AirNode(from));
- }
- if (!nodes.containsKey(to)) {
- nodes.put(to, new AirNode(to));
- }
- nodes.get(from).outgoing.add(nodes.get(to));
- }
- Vector result = new Vector();
- HashSet visited = new HashSet();
- //start the dfs on graph
- for (AirNode node : nodes.values()) {
- dfs(node, visited, result);
- }
- return result;
- }
- public static void dfs(AirNode node, HashSet visited,
- Vector result) {
- if (visited.contains(node.airport)) {
- return;
- }
- visited.add(node.airport);
- for (AirNode curr : node.outgoing) {
- dfs(curr, visited, result);
- }
- result.insertElementAt(node.airport, 0);
- }
- }
- class AirNode {
- String airport;
- Set outgoing;
- public AirNode(String airport) {
- this.airport = airport;
- outgoing = new HashSet();
- }
- public boolean equals(Object obj) {
- if (obj == null) {
- return false;
- }
- if (this == obj) {
- return true;
- }
- if (obj instanceof AirNode) {
- AirNode node = (AirNode) obj;
- return this.airport.equals(node.airport);
- }
- return false;
- }
- public int hashCode() {
- return this.airport.hashCode();
- }
- }