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.