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.