According to this image , I'm trying to write a program that finds all paths from vertex 1 to 7.
Exactly like this output. I used DFS in my code using stack , but I received stack overflow error. I want to have each of these outputs stored in list to print like this:
1--> 2--> 5--> 8--> 7
1--> 2--> 5--> 7
1--> 2--> 5--> 3--> 6--> 7
--------------------------------
1--> 3--> 6--> 7
1--> 3--> 5--> 7
1--> 3--> 5--> 8--> 7
how can I do that?
Here is my code
public List<Integer> m(int root,int destination){
Stack<Integer> stack=new Stack<>();
List<Integer> list=new ArrayList<>();
Set<Integer> seen=new HashSet<>();
stack.push(root);
seen.add(root);
list.add(root);
while (!stack.isEmpty()&&!seen.contains(destination)){
for (Edge y:neighbors.get(root)){
if(!seen.contains(y.end)){
stack.push(y.end);
seen.add(y.end);
list.add(y.end);
m(stack.pop(),destination);
}
}
}
return list;
}