Breadth First Search: Shortest Reach

  • + 0 comments

    shortest python solution

    def bfs(n, m, edges, s):
        graph = {i: [] for i in range(1, n+1)}
        for i in edges:
            u, v = i
            graph[u].append(v)
            graph[v].append(u)
        
        q = deque()
        distance = [-1] * (n+1)
        distance[s] = 0
        q.append(s)
        
        while q:
            node = q.popleft()
            for neighbor in graph[node]:
                if distance[neighbor] == -1:
                    distance[neighbor] = distance[node] + 6
                    q.append(neighbor)
        distance.remove(0)
        return distance[1:]