import java.util.*;
class GFG {
// Function to perform DFS and topological sorting
static void topologicalSortUtil(String v, Map<String, String> mp, Map<String, Integer> visited, Stack<String> st) {
// mark current node as visited
visited.put(v, 1);
// recur for adjacent vertex
if (mp.containsKey(v) && visited.getOrDefault(mp.get(v), 0) == 0)
topologicalSortUtil(mp.get(v), mp, visited, st);
// push current vertex in stack
if (!v.isEmpty())
st.push(v);
}
// Function to perform topological sort
static List<String> topologicalSort(Map<String, String> mp) {
int V = mp.size();
// stack to store the result
Stack<String> st = new Stack<>();
Map<String, Integer> visited = new HashMap<>();
// Call the recursive helper function to store
// Topological Sort starting from all vertices
for (String i : mp.keySet()) {
if (visited.getOrDefault(i, 0) == 0)
topologicalSortUtil(i, mp, visited, st);
}
List<String> ans = new ArrayList<>();
// append contents of stack
while (!st.isEmpty()) {
ans.add(st.pop());
}
return ans;
}
static List<List<String>> findItinerary(List<List<String>> arr) {
// map the list of tickets
Map<String, String> mp = new HashMap<>();
for (List<String> i : arr) {
mp.put(i.get(0), i.get(1));
}
List<String> res = topologicalSort(mp);
List<List<String>> ans = new ArrayList<>();
for (int i = 0; i < res.size() - 1; i++) {
ans.add(Arrays.asList(res.get(i), res.get(i + 1)));
}
return ans;
}
public static void main(String[] args) {
List<List<String>> arr = Arrays.asList(
Arrays.asList("Chennai", "Bangalore"),
Arrays.asList("Bombay", "Delhi"),
Arrays.asList("Goa", "Chennai"),
Arrays.asList("Delhi", "Goa")
);
List<List<String>> res = findItinerary(arr);
for (List<String> i : res) {
System.out.println(i.get(0) + " -> " + i.get(1));
}
}
}