You get an undirected graph with n vertices, labeled
0 to n - 1. Each entry
edges[i] = [ui, vi] joins vertices
ui and vi. You can follow
an edge in both directions.
Return true if you can walk along edges from vertex
source to vertex destination. Otherwise, return
false. A vertex always reaches itself.
Example 1:
Input: n = 5, edges = [[3,0],[0,4],[4,2],[2,1],[1,4]], source = 3, destination = 1 Output: true Explanation: The blue edges show the path 3 → 0 → 4 → 1. The path 3 → 0 → 4 → 2 → 1 also works.
Example 2:
Input: n = 6, edges = [[0,5],[5,2],[1,3],[3,4]], source = 2, destination = 4 Output: false Explanation: The graph has two separate parts. From 2, you can only reach 5 and 0. No edge leads to the part with 1, 3 and 4.
Example 3:
Input: n = 3, edges = [[1,2]], source = 0, destination = 0 Output: true Explanation: Vertex 0 has no edges. But source and destination are the same vertex. The walk starts and ends right there.
Constraints:
- 2 to 200,000 vertices.
- At most 200,000 entries in
edges. - Every vertex in
edgesis from0ton - 1. So aresourceanddestination. - No edge joins a vertex to itself.
- The same edge can be listed twice, for example as
[1, 4]and[4, 1].
Walkthroughs of the solution. Try the steps first, then watch to compare approaches.
Free plan: 30 tutor messages. PRO is unlimited.
Saved
Ctrl + Enter to check
