AlgoFrames

Is this sequence a path?

Standard · Write code · about 10 min

Return true when walk is a path in graph: every two neighbours in walk are joined by an edge, and no vertex appears twice.

In a directed graph an edge [u, v] only lets you step from u to v. An empty walk is not a path; a single vertex is a path of length 0.

Example 1

Input:

[{"n":5,"edges":[[0,1],[0,2],[1,2],[1,3],[2,3],[3,4]],"directed":false},[0,1,3,4]]

Output:

true

Edges 0-1, 1-3 and 3-4 exist and nothing repeats.

Example 2

Input:

[{"n":5,"edges":[[0,1],[0,2],[1,2],[1,3],[2,3],[3,4]],"directed":false},[1,3,2,1]]

Output:

false

A cycle repeats its start, so it is not a path.

Constraints

  • 1 ≤ n ≤ 1,000
  • 0 ≤ edges.length ≤ 2,000
  • 0 ≤ walk.length ≤ 1,000
  • 0 ≤ walk[i] < n

Learn the idea first: Graphs: vertices, edges, directed, weighted, degree, paths, a visual lesson.

More Graphs: vertices, edges, directed, weighted, degree, paths problems