Published
- 1 min read
All Paths From Source to Target DFS
All Paths From Source to Target Given a directed acyclic graph (DAG) of n nodes labeled from 0 to n - 1, find all possible paths from node 0 to node n - 1 and return them in any order. The graph is given as follows: graph[i] is a list of all nodes you can visit from node i (i.e., there is a directed edge from node i to node graph[i][j]).
- Start with source node, have the adjacency list already prepared
- keep adding the node to the path list, stack is a structure which contains list of paths.
- whenever given node equals destination a path is found,add the path to the result list
- repeat this process till stack gets empty
- Whats the termination condition for printing all the paths ???? stack needs to be empty
List<List<Integer>> result = new ArrayList();
Map<Integer, List<Integer>> mp = new HashMap();
Stack<List<Integer>> stack = new Stack();
private List<List<Integer>> allPathsFromSourceToDestination(Node node, int [] visited, Node destination) {
while(!stack.isEmpty){
List<Integer> listOfPaths = stack.pop() ;
if(listOfPaths.get(paths.size()-1) == destination) {
result.add(new ArrayList().add(listOfPaths));
} else {
List<Integer> neighbours = mp.get(node);
List<Integer> newPaths = new ArrayList(listOfPaths);
for(Node neighbour : neighbours) {
newPaths.add(neighbour);
stack.push(neighbour);
}
}
}
}