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
LeetCode-এ খুলুন ↗

আমি 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.