-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTracePath.java
More file actions
79 lines (62 loc) · 2.09 KB
/
TracePath.java
File metadata and controls
79 lines (62 loc) · 2.09 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
package datastructure.hashtable;
import java.util.HashMap;
import java.util.Map;
/**
* The type Trace path.
*/
public class TracePath {
/**
* Trace path string.
*
* @param map the map
* @return the string
*/
public static String tracePath(Map<String, String> map) {
String result = "";
//Create a reverse Map of given map i.e if given map has (N,C) then reverse map will have (C,N) as key value pair
//Traverse original map and see if corresponding key exist in reverse Map
//If it doesn't exist then we found our starting point.
//After starting point is found, simply trace the complete path from original map.
HashMap<String, String> reverseMap = new HashMap<>();
//To fill reverse map, iterate through the given map
for (Map.Entry<String, String> entry : map.entrySet())
reverseMap.put(entry.getValue(), entry.getKey());
//Find the starting point of itinerary
String from = "";
//Check if graph is disconnected
int count = 0;
for (Map.Entry<String, String> entry : map.entrySet()) {
if (!reverseMap.containsKey(entry.getKey())) {
count++;
from = entry.getKey();
//break;
}
}
if (count > 1) {
return "null"; // Disconnected graph
}
//Trace complete path
String to = map.get(from);
while (to != null) {
result += from + "->" + to + ", ";
from = to;
to = map.get(to);
}
//System.out.println(result);
return result;
}
/**
* The entry point of application.
*
* @param args the input arguments
*/
public static void main(String[] args) {
HashMap<String, String> hMap = new HashMap<>();
hMap.put("NewYork", "Chicago");
hMap.put("Boston", "Texas");
hMap.put("Missouri", "NewYork");
hMap.put("Texas", "Missouri");
String actual_output = tracePath(hMap);
System.out.println(actual_output);
}
}