Tech for good

[Codepath/BFS, Graph] Find Path 본문

IT/Computer Science

[Codepath/BFS, Graph] Find Path

Diana Kang 2025. 8. 12. 00:53

from collections import deque, defaultdict

def has_path(adjacency_dict, start, destination):
    # Write your code here
    if start == destination:
        return True
        
    graph = defaultdict(list, adjacency_dict)
    
    q = deque([start])
    visited = set([start])

    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