oneby7

Graphs Graph basics

433. All Paths From Source to Target

Medium

You are given a directed graph with n vertices, numbered from 0 to n - 1, as an adjacency list. graph[i] lists every vertex that an edge from vertex i points to. An empty graph[i] means no edge leaves vertex i. The graph has no cycle: following the edges never leads back to a vertex already passed. Such a graph is called a directed acyclic graph, or DAG.

Return every path from vertex 0 to vertex n - 1. A path starts at 0, follows one edge at a time in the direction it points, and ends when it reaches n - 1. Give each path as the list of its vertices in the order it visits them, with both ends included. Two paths are different when their lists are different, even if they share some vertices. If no path reaches n - 1, return [].

The paths can come back in any order. The examples sort them the way a dictionary sorts words, comparing the first vertices, then the second vertices, and so on.

Example 1

012345

Input: graph = [[1, 2], [3, 5], [3, 4], [5], [], []]

Output: [[0,1,3,5],[0,1,5],[0,2,3,5]]

Explanation: Three paths reach vertex 5: 0 → 1 → 3 → 5, 0 → 1 → 5 and 0 → 2 → 3 → 5. Two of them pass through vertex 3, and both count. The walk 0 → 2 → 4 gets stuck at 4, since no edge leaves it.

Example 2

012

Input: graph = [[1], [], [1]]

Output: []

Explanation: From vertex 0 the only edge goes to vertex 1, and no edge leaves 1. The edge between 1 and 2 points from 2 to 1, so it cannot be used to reach 2.

Example 3

01

Input: graph = [[1], []]

Output: [[0,1]]

Explanation: The single edge 0 → 1 is the only path, and the path lists both of its ends.

Check your understanding

Work out the answer for this input before you write any code.

graph = [[1, 2], [3], [3], []]

Constraints

  • n == graph.length
  • 2 ≤ n ≤ 18
  • 0 ≤ graph[i][j] < n
  • graph[i][j] ≠ i
  • All the values in graph[i] are different.
  • The graph has no cycle.

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.