All Paths From Source to Target LeetCode solution in Java
1// Approach : Using dfs+ backtracking we can solve it23class Solution {4public List<List<Integer>> allPathsSourceTarget(int[][] graph) {5List<List<Integer>> ans = new ArrayList<>();6List<Integer> temp = new ArrayList<>();7boolean[] visit = new boolean[graph.length];8helper(graph, 0, graph.length - 1, ans, temp, visit);910return ans;11}1213public void helper(14int[][] graph,15int src,16int dest,17List<List<Integer>> ans,18List<Integer> temp,19boolean[] vis) {20vis[src] = true;21temp.add(src);2223if (src == dest) {24List<Integer> b = new ArrayList<>();25for (int h : temp) {26b.add(h);27}28ans.add(b);29}3031for (int i : graph[src]) {32if (vis[i] != true) {33helper(graph, i, dest, ans, temp, vis);34}35}3637vis[src] = false;38temp.remove(temp.size() - 1);39}40}