Tech for good

[Leetcode/DFS, BFS, Graph] 1971. Find if Path Exists in Graph 본문

IT/Computer Science

[Leetcode/DFS, BFS, Graph] 1971. Find if Path Exists in Graph

Diana Kang 2025. 8. 8. 11:05

class Solution:
    def validPath(self, n: int, edges: List[List[int]], source: int, destination: int) -> bool:
        # 1. Make a graph
        ## To figure out neighbor using hash-map
        ## 0 => [1,2]

        graph = defaultdict(list)

        for u, v in edges:
            graph[u].append(v)
            graph[v].append(u)

        # 2. BFS from source
        q = deque([source])
        visited = set([source])

        while q:
            curr = q.popleft()

            if curr == destination:
                return True
            
            for neighbor in graph[curr]:
                if neighbor not in visited:
                    visited.add(neighbor)
                    q.append(neighbor)

        return False