Given edges
Edges: { {1,2},
{1,3},
{3,4},
{3,5},
{5,6}};
Find all possible paths from any node to any node ( Note moves only downwards from root node ).
Expected Output:
1->2
1->3
1->3->4
1->3->5
1->3->5->6
3->4
3->5
5->6
3->5->6
I've written code for this. But I'm only able to get: 1->2, 1->3, 3->4, 3->5, 5->6.
Code: https://leetcode.com/playground/bEp484tr
static void dfs(int source){
Stack<Integer> stack = new Stack<>();
HashSet<Integer> visited = new HashSet<>();
int currVertex;
String path = "";
stack.push(source);
visited.add(source);
while(!stack.isEmpty()){
currVertex = stack.pop().intValue();
path += currVertex;
if(!adjList.containsKey(currVertex)){
continue;
}
// Visiting its neighbours
for(int neighbour : adjList.get(new Integer(currVertex))){
if(!visited.contains(new Integer(neighbour))){
path += neighbour;
visited.add(neighbour);
stack.push(neighbour);
System.out.println(path);
// Undo
path = path.substring(0, path.length() - 1);
}
}
path = "";
}
}
Could you please help me to understand where I've gone wrong, why only the 2 digits output is getting printed?
Also, How do I handle the case for 3->5->6? This is the case where the parent node is not the root node.