Print all paths from vertex $v_0$ to vertex $v_1$
Q1. How to store a graph
A1. We can use HashMap to store a vertex and all its children
Create Edge class to store two vertexes
Convert list of Edges to HashMap
class Edge{
String beg;
String end;
public Edge(String beg, String end){
this.beg = beg;
this.end = end;
}
}
Map < String, Set < String>> map = new HashMap<>();
public static Map < String, Set < String>> geneGraph(List < Edge> ls){
Map> map = new HashMap<>();
for(Edge e : ls){
var set = map.get(e.beg);
if( set == null){
set = new HashSet<>();
}
set.add(e.end);
map.put(e.beg, set);
}
return map;
}
Print all paths from vertex a to vertex b
public static void printAllPath(Map <String, Set <String>> map, String a, String b, List < String> ls){
Set set = map.get(a);
if(set != null){
for(String e : set){
if( e != b){
printAllPath(map, e, b, append(ls, e));
}else{
pl("");
List rs = append(ls, e);
printList(rs);
}
}
}
}
Find the longest path from vertex a to vertex b
public static int printAllPathShortest(Map<String, Set<String>> map, String a, String b, List<String> ls){
Set<String> set = map.get(a);
int max = Integer.MIN_VALUE;
if(set != null){
for(String e : set){
if( e != b){
// Overflow in Integer here
int n = printAllPathShortest(map, e, b, append(ls, e)) + 1;
if(n > max){
max = n;
}
}else{
List<String> rs = append(ls, e);
printList(rs);
return 0;
}
}
}
return max;
}