Find if Path Exists in Graph

Easy#1971

There are n vertices and a list of undirected edges. Say whether you can walk from the vertex source to the vertex destination along the edges. Our example: 5 vertices, edges 0–1, 2–3, 1–2, from 0 to 3 → true.

input
n: the number of vertices, numbered from 0 to n - 1. edges: the undirected edges, each [u, v] joining u and v. source and destination: two vertices.
returns
true if you can walk from source to destination along the edges; otherwise false. A vertex is reached from itself.
constraints
  • 1 ≤ n ≤ 400
  • 0 ≤ edges.length ≤ 1000
  • edges[i] = [u, v], 0 ≤ u, v < n, u ≠ v
  • no edge is given twice, either way round
  • 0 ≤ source, destination < n
our 11 tests keep to them
examples
Open a test in the tests panel: it shows the input and the expected answer.
/**
 * @param {number} n
 * @param {number[][]} edges
 * @param {number} source
 * @param {number} destination
 * @return {boolean}
 */
function validPath(n, edges, source, destination) {

}
Ctrl ↵
format
reset

saved in this browser

11 tests · limit 3 s

Stuck?

See the solution run step by step on our example, then why it works and its complexity.

Watch the walkthrough →

Next: more union-find problems

Pattern “Union-Find” →

The problem and its statement belong to LeetCode. Here are our own retelling, example and solution. Patterns Hero is not affiliated with LeetCode.