0

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;
}
MD. Khairul Basar
  • 4,976
  • 14
  • 41
  • 59
mnreat
  • 11
  • 2

1 Answers1

0

I think this should be in the separate method

Stack<Integer> stack = new Stack<>();
List<Integer> list = new ArrayList<>();
Set<Integer> seen = new HashSet<>();

stack.push(root);
seen.add(root);
list.add(root);

Something like

class PathFinder {

    private Stack<Integer> stack = new Stack<>();

    private List<Integer> list = new ArrayList<>();

    private Set<Integer> seen = new HashSet<>();

    public List<Integer> find(int root, int destination) {
      // perhaps, it can be in the m()
      stack.push(root);
      seen.add(root);
      list.add(root);

      m(root, destination);

      return list;
    }

    private void m(int root, int destination) {

    }

}
v.ladynev
  • 19,275
  • 8
  • 46
  • 67