Find if Path Exists in Graph
LeetCode 1971 · आसान · समाधान, intuition और कदम-दर-कदम वॉकथ्रू
BFS reachability.
मैंने Find if Path Exists in Graph (LeetCode 1971) ऐसे हल किया — Graph Fundamentals / DFS-BFS पैटर्न का एक आसान प्रॉब्लम। नीचे: intuition, कदम-दर-कदम approach, मेरा accepted Python कोड, animated test cases और line-by-line debugger।
नीचे का विवरण अंग्रेज़ी में है।
Intuition
Build the undirected graph and BFS from the source; the destination is reachable exactly when BFS visits it.
Approach
- 1
Adjacency list both ways.
- 2
BFS from source; return True when destination is popped.
मैंने कैसे हल किया
BFSPythonO(V+E) time
class Solution:
def validPath(self, n: int, edges: List[List[int]], source: int, destination: int) -> bool:
adj = defaultdict(list)
for u,v in edges:
adj[u].append(v)
adj[v].append(u)
q = deque([source])
visited = set()
while q:
node = q.popleft()
if node==destination:
return True
for adj_node in adj[node]:
if adj_node not in visited:
visited.add(adj_node)
q.append(adj_node)
return FalseFind if Path Exists in Graph — अक्सर पूछे जाने वाले प्रश्न
Find if Path Exists in Graph के पीछे intuition क्या है?
Build the undirected graph and BFS from the source; the destination is reachable exactly when BFS visits it.
Find if Path Exists in Graph (LeetCode 1971) कैसे हल करें?
1. Adjacency list both ways. 2. BFS from source; return True when destination is popped.
Find if Path Exists in Graph की time और space complexity क्या है?
Time: O(V + E)। Space: O(V + E)। (Accepted approach: BFS।)
Find if Path Exists in Graph में आम गलतियाँ क्या हैं?
source == destination is trivially True.