Menu
CoddyTech

Find if Path Exists in Graph

An undirected graph has n nodes, numbered 0 to n-1. Each entry [u, v] of edges connects nodes u and v, and you can walk an edge in either direction. Return true if you can walk from source to destination along the edges, and false otherwise. A node can always reach itself.

Function

validPath(n: integer, edges: integer-2d-array, source: integer, destination: integer) → boolean
ninteger
the number of nodes
edgesinteger-2d-array
the edges, each a pair [u, v] of connected nodes
sourceinteger
the node you start from
destinationinteger
the node you want to reach
Returnsboolean
whether some path joins source and destination

Constraints

  • 2 ≤ n ≤ 104
  • 1 ≤ edges.length ≤ 5000
  • edges[i] = [u, v] with 0 ≤ u, v ≤ n-1 and u ≠ v
  • No edge appears twice, in either direction.
  • 0 ≤ source, destination ≤ n-1

Examples

Input
n = 6edges = [[0, 1], [1, 2], [2, 3], [4, 5]]source = 0destination = 3
Output
true
Explanation
The walk 0 → 1 → 2 → 3 uses three edges, so node 3 is reachable. Nodes 4 and 5 form a separate piece that the walk never needs.

lock icon+16 hidden tests on Submit

challenge icon

Follow-up

Suppose the edges are one-way: [u, v] lets you walk from u to v only. Which of the three approaches still work, and what do you change in them?

Reset code
def validPath(n, edges, source, destination):
    # Write code here
Test cases

Case 1

Case 2

Input

n = 6
edges = [[0, 1], [1, 2], [2, 3], [4, 5]]
source = 0
destination = 3

Expected

true