You are viewing a single comment's thread. Return to all comments →
python 3 solution:
from collections import deque class Graph: def __init__(self, num_nodes): self.num_nodes = num_nodes self.nodes = {i: [] for i in range(1, self.num_nodes+1)} def connect(self, start, end): self.nodes[start+1].append(end+1) self.nodes[end+1].append(start+1) def find_all_distances(self, start_node): start_node += 1 queue = deque([[start_node]]) res = [-1]*self.num_nodes updated = [] i = 0 while len(queue) > 0: val = 6*i to_update = queue.popleft() next_set = [] for node in to_update: if node in updated: continue res[node-1] = val updated.append(node) next_set += self.nodes[node] if len(next_set) == 0: break queue.append(next_set) i += 1 res.pop(start_node-1) print(' '.join(str(v) for v in res))
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 →
python 3 solution: