Tensorum
YouTubeशिकायला सुरुवात करा
LeetCode 1971 · Graph Fundamentals / DFS-BFS

Find if Path Exists in Graph

LeetCode 1971 · सोपा · उपाय, intuition आणि टप्प्याटप्प्याने वॉकथ्रू

BFS reachability.

सोपाDepth-First SearchBreadth-First SearchUnion-FindGraph Theory

मी 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. 1

    Adjacency list both ways.

  2. 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 False
स्टेप-थ्रू लोड होत आहे…

Find 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.