Village Road Network - Problem

There are n villages numbered from 0 to n - 1. You are given a 2D array roads where each roads[i] = [u, v] means there is a bidirectional road between village u and village v.

Given two integers source and destination, return true if a traveler can reach destination from source using the available roads, or false otherwise.

Input & Output

Example 1 — Disconnected Villages
$ Input: n = 6, roads = [[0,1],[0,2],[3,5],[5,4],[4,3]], source = 0, destination = 5
Output: false
💡 Note: Villages 0,1,2 form one cluster. Villages 3,4,5 form another. No road connects the two clusters.
Example 2 — Connected Villages
$ Input: n = 3, roads = [[0,1],[1,2],[2,0]], source = 0, destination = 2
Output: true
💡 Note: All villages are connected. Route: 0 → 1 → 2 or directly 0 → 2.
Example 3 — Same Village
$ Input: n = 1, roads = [], source = 0, destination = 0
Output: true
💡 Note: Source equals destination — the traveler is already there.

Constraints

  • 1 ≤ n ≤ 2 × 10^5
  • 0 ≤ edges.length ≤ 2 × 10^5
  • edges[i].length == 2
  • 0 ≤ u, v < n
  • 0 ≤ source, destination < n

Visualization

Tap to expand
Village Road Network INPUT Undirected Graph: n=6 0 1 2 3 4 5 source = 0 destination = 5 Question: Can we reach node 5 starting from node 0? ALGORITHM STEPS 1 Build Adjacency List 0→[1,2] 1→[0] 2→[0] 3→[5,4] ... 2 BFS from Source Queue: [0], Visited: {0} 3 Explore Neighbors Dequeue, check dest, enqueue neighbors 4 Check Result Queue empty? → destination not found Execution Trace: step dequeue neighbors queue init — — [0] 1 0 1,2 [1,2] 2 1 0(vis) [2] 3 2 0(vis) [] — EMPTY — — Node 5 never reached! FINAL RESULT Component Analysis: Component A 0 1 2 ← source Component B 3 4 5 ← dest Different components! No bridge connects them Output: false 💡 Key Insight: Two nodes are reachable if and only if they belong to the same connected component. BFS/DFS explores from source in O(V+E). Union-Find checks connectivity in near O(1) per query. TutorialsPoint - Village Road Network | BFS Traversal Approach
Asked in
Amazon 52 Google 38 Meta 28 Microsoft 25
3 Views
High Frequency
~15 min Avg. Time
0 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen