You are viewing a single comment's thread. Return to all comments →

from collections import defaultdict class Graph: def __init__(self, n): self.graph = defaultdict(list) self.n_nodes = n def connect(self, u, v): self.graph[u].append(v) self.graph[v].append(u) def bfs(self, s): queue = [s] dists = {s: 0} while queue: n = queue.pop(0) for i in self.graph[n]: if i not in dists: dists[i] = dists[n] + 6 queue.append(i) return dists def find_all_distances(self, s): dists = self.bfs(s) ans = [] for node in range(self.n_nodes): if node == s: continue elif node not in dists: ans.append(-1) else: ans.append(dists[node]) print(" ".join(map(str, ans)))

Seems like cookies are disabled on this browser, please enable them to open this website

## BFS: Shortest Reach in a Graph

You are viewing a single comment's thread. Return to all comments →

## Easy to understand python3