Practice
JavaScriptData StructuresReactConcepts
Sign in
← Back to problems

Has Path

Graphseasy

Given `n` nodes, an undirected `edges` list, a `src`, and a `dst`, implement `hasPath(n, edges, src, dst)` returning whether a path exists from `src` to `dst`.

Sample tests

Input: hasPath(3, [[0,1],[1,2]], 0, 2)
Output: true
Input: hasPath(3, [[0,1]], 0, 2)
Output: false

+ 1 hidden test run on Submit.

Hints

Common pitfalls
  • No visited set loops forever on cyclic graphs.

Learning resources

  • Wikipedia: Graph traversal
Approach & explanation (try first)

DFS or BFS from the source reaches the destination if a path exists. O(V + E) time.

Loading...
⌘/Ctrl + Enter

Run your code to see results.