Skip to main content
Back to problems
Leetcode
Medium
Graphs
Graph Connectivity
Sets
Google
Find If Path Exists in Graph

Determine whether two vertices in an undirected graph are connected by any path.

Acceptance 100%
Problem Statement

Problem

You are given an undirected graph with n vertices labeled from 0 to n - 1, a list of edges, a source vertex source, and a destination vertex destination.

Return true if there exists any path from source to destination; otherwise return false.

A path may use any number of intermediate vertices, but it must follow the edges of the graph.

Notes

  • The graph is undirected, so each edge can be used in both directions.
  • You only need to determine reachability, not the actual path.
  • Multiple edges and self-loops are not important for the core idea, but your solution should still behave correctly.

Input Format

  • n: number of vertices
  • edges: list of undirected edges, where each edge is [u, v]
  • source: starting vertex
  • destination: target vertex

Output Format

  • Return true if destination is reachable from source, otherwise return false.

Constraints

  • 0 <= source, destination < n
  • The graph has n vertices labeled 0..n-1
  • edges[i] = [u, v] represents an undirected edge between u and v
  • n and edges.length are expected to be within typical interview-sized limits for graph traversal

Hints

  • Think in terms of reachability: if you can visit all nodes connected to source, can you tell whether destination is among them?
  • You may solve this with either graph traversal or a connectivity data structure.

Input Format

  • n: number of vertices
  • edges: undirected edge list [[u1, v1], [u2, v2], ...]
  • source: start vertex
  • destination: target vertex

Output Format

  • Return a boolean value: true if a path exists, otherwise false.

Constraints

  • Undirected graph
  • Vertices are labeled from 0 to n - 1
  • source and destination are valid vertex labels
  • Return reachability only; do not construct the path
Examples
Sample cases returned by the problem API.

Example 1

Input

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

Output

true

Explanation

There is a direct edge from 0 to 2, so a path exists.

Example 2

Input

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

Output

false

Explanation

Vertices 0 and 5 belong to different connected components, so no path exists.

Premium problem context

Unlock deeper context for this problem

Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.

Guided hints
Editorial and discussion links
Concept map and variants
Sign in to unlock
Track your progress
Sign in to bookmark this problem, save notes, and manage its revision plan.