📘
Find if Path Exists in Graph
EasyGraphs & BFS/DFS
Given n nodes, undirected edges, and two nodes source and destination, return True if a path exists between them.
Input: first line = n, second = edges as u:v comma-separated (or 'none'), third = source destination.
Example:
Input:
3 0:1,1:2,2:0 0 2
Output:
True
Reasoning:
- The graph is constructed with n=3 nodes and undirected edges between nodes 0 and 1, 1 and 2, and 2 and 0.
- The edges create a cycle: 0↔1↔2↔0, allowing for a path between any two nodes.
- A path exists from the
sourcenode 0 to thedestinationnode 2, as they are directly connected through node 1 and also through the cycle 0↔2. - The function returns
Truebecause a path is found between thesourceanddestinationnodes.
Constraints:
- 1 <= n <= 2 * 10^5
- 0 <= edges.length <= 2 * 10^5
Editor
Python 3.13.1
Test Results
0/0Run code to see test results.