Skip to content

797. All Paths From Source to Target 👍

  • Time: $O(n \cdot 2^n)$
  • Space: $O(n \cdot 2^n)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution {
 public:
  vector<vector<int>> allPathsSourceTarget(vector<vector<int>>& graph) {
    vector<vector<int>> ans;
    dfs(graph, 0, {0}, ans);
    return ans;
  }

 private:
  void dfs(const vector<vector<int>>& graph, int u, vector<int>&& path,
           vector<vector<int>>& ans) {
    if (u == graph.size() - 1) {
      ans.push_back(path);
      return;
    }

    for (const int v : graph[u]) {
      path.push_back(v);
      dfs(graph, v, std::move(path), ans);
      path.pop_back();
    }
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
  public List<List<Integer>> allPathsSourceTarget(int[][] graph) {
    List<List<Integer>> ans = new ArrayList<>();
    dfs(graph, 0, new ArrayList<>(List.of(0)), ans);
    return ans;
  }

  private void dfs(int[][] graph, int u, List<Integer> path, List<List<Integer>> ans) {
    if (u == graph.length - 1) {
      ans.add(new ArrayList<>(path));
      return;
    }

    for (final int v : graph[u]) {
      path.add(v);
      dfs(graph, v, path, ans);
      path.remove(path.size() - 1);
    }
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
class Solution:
  def allPathsSourceTarget(self, graph: list[list[int]]) -> list[list[int]]:
    ans = []

    def dfs(u: int, path: list[int]) -> None:
      if u == len(graph) - 1:
        ans.append(path)
        return

      for v in graph[u]:
        dfs(v, path + [v])

    dfs(0, [0])
    return ans