Problem 504713 · easy · Level 05 Advanced Algorithms & Graphs

Is There a Path?

graphs · BFS · adjacency list

An undirected graph has n nodes labelled 0 .. n-1. It is given as n together with a list edges where edges[i] = [u, v] means there is an edge between u and v. Return True if there is a path from source to destination, otherwise False. A node always has a path to itself.

Examples

Input:  n = 4, edges = [[0,1],[1,3],[3,2]], source = 0, destination = 2
Output: True
Explanation: 0 -> 1 -> 3 -> 2.

Input:  n = 5, edges = [[0,4],[1,2],[2,3]], source = 4, destination = 3
Output: False
Explanation: {0,4} and {1,2,3} are separate components.

Constraints

  • 1 <= n <= 2 * 10**4, 0 <= len(edges) <= 5 * 10**4
  • Edges may be repeated; there are no self-loops.
  • Target O(V + E) time.

Goals

  • Build an adjacency list from an undirected edge list
  • Run a BFS/DFS with a visited array and stop early when the destination is reached
Starting Python…