def __bfs(g, src, parents): q = Queue() q.enqueue(src) while not q.isempty(): cur = q.dequeue() for succ in g.adjlists[cur]: if parents[succ] is None: parents[succ] = cur q.enqueue(succ)
def __bfs_mat(g, src, parents): q = Queue() q.enqueue(src) while not q.isempty(): cur = q.dequeue() # For succ in g.adjlists[cur] for succ in range(g.order): if g.adj[cur][succ]: if parents[succ] is None: parents[succ] = cur q.enqueue(succ)
def __bfs_path(g, src, dst, parents, dist): g = Queue() q.enqueue(src) while not q.isempty(): cur = q.dequeue() for succ in g.adjlists[cur]: if parents[succ] is None: parents[succ] = cur dist[succ] = dist[cur] + 1 if succ == dst: return q.enqueue(succ)
def serialize_bfs(t): q = Queue() q.enqueue(t) parents = [-1] * (t.key + 1) while not q.isempty(): cur = q.dequeue() for child in cur.children: if child.key >= len(parents): parents += [-1] * (child.key - len(parents) + 1) parents[child.key] = cur.key q.enqueue(child) return parents
def width(t): w, wcur = 0, 0 q = Queue() q.enqueue(t) q.enqueue(None) while not q.isempty(): cur = q.dequeue() if not cur: w = max(w, wcur) wcur = 0 if not q.isempty(): q.enqueue(None) else: wcur += 1 for child in cur.children: q.enqueue(child) return w
def width_bin(t): w, wcur = 0, 0 q = Queue() q.enqueue(t) q.enqueue(None) while not q.isempty(): cur = q.dequeue() if not cur: w = max(w, wcur) wcur = 0 if not q.isempty(): q.enqueue(None) else: wcur += 1 child = cur.child while child: q.enqueue(child) child = child.sibling return w
def distance(g, src, dmin, dmax): dist = [None] * g.order q = Queue() q.enqueue(src) dist[src] = 0 last = 0 if dmin == 0: print(src) while not q.isempty(): cur = q.dequeue() if dist[cur] >= dmin and dist[cur] != last: print() last = dist[cur] if dist[cur] >= dmin - 1: for s in range(g.order): if g.adj[cur][s] and dist[dist] is None: print(s, end=' ') if dist[cur] < dmax - 1: for s in range(g.order): if g.adj[cur][s] and dist[s] is None: dist[s] = dist[cur] + 1 q.enqueue(s) print()
def dist_from_start(G, src, dmin, dmax): parents = [None] * G.order dist = 0 res = [] q = Queue() q.enqueue(src) q.enqueue(None) parents[src] = -1 while not q.isempty(): cur = q.dequeue() if cur is None: if q.isempty(): return res q.enqueue(None): dist += 1 else: if dist < dmax: for succ in range(g.order): if G.adj[cur][succ]: if parents[succ] is None: parents[succ] = curr q.enqueue(succ) if dist >= dmin - 1: res.append(succ)
# ## BFS # # # # 15 # 3 8 9 # -6 10 11 2 5 # 0 4 # # 2.2 question 3 # In[12]: from algopy.queue import Queue q = Queue() for i in range(10): q.enqueue(i) while not q.isempty(): print(q.dequeue()) # In[13]: def width(t): w, wcur = 0, 0 q = Queue() q.enqueue(t) q.enqueue(None) while not q.isempty(): cur = q.dequeue()