Created
December 10, 2019 19:09
-
-
Save ehzawad/9dc4659e12d6b6b0d1f47641b5e5e126 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from collections import deque | |
class BFSResult: | |
def __init__(self): | |
self.level = {} | |
self.parent = {} | |
class Graph: | |
def __init__(self): | |
self.adj = {} | |
def add_edge(self, u, v): | |
if self.adj[u] is None: | |
self.adj[u] = [] | |
self.adj[u].append(v) | |
def bfs(g, s): | |
r = BFSResult() | |
r.parent = {s: None} | |
r.level = {s: 0} | |
queue = deque() | |
queue.append(s) | |
while queue: | |
u = queue.popleft() | |
for n in g.adj[u]: | |
if n not in level: | |
r.parent[n] = u | |
r.level[n] = r.level[u] + 1 | |
queue.append(n) | |
return r | |
g = Graph() | |
g.add_edge(3, 5) | |
g.add_edge(5, 3) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment