Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Lära Restoring Shortest Path | Practice
Breadth First Search

book
Restoring Shortest Path

BFS searching shortest path

That was hard! But now let's implement a method to find the shortest path between two vertices, not only length.

To do that, you have to know for each node where did it come from. So, let's add list pred that contains predcessor for i node. At the beginning, pred contains only -1.

Uppgift

Swipe to start coding

Modify bfs(start, end) so it returns a list of vertices between start and end nodes (both inclusive). If there is no path, return an empty list.

Do not forget to keep the path.

Var allt tydligt?

Hur kan vi förbättra det?

Tack för dina kommentarer!

Avsnitt 2. Kapitel 4
class Graph:
def __init__(self, vertices):
# init graph with its vertices
self.graph = {v : [] for v in vertices}

def addEdge(self, u, v):
self.graph[u].append(v)
def __str__(self):
out = ""
for vertex in self.graph:
out += vertex + ":"+self.graph[vertex]
return out
def bfs(self, start, end):
q = [] # queue

# list of predcessors: pred[i] contains the parent node
pred = [-1 for _ in self.graph.keys()]

visited = [-1 for v in self.graph.keys()]
q.append(start)
visited[start] = 0

while len(q)>0:
node = q.pop(0)
for vertex in self.graph[node]: # iterate neighbors, update q, visited and pred
# put your code here


return _________

g=Graph([0,1,2,3,4,5])
g.addEdge(0,1)
g.addEdge(2,1)
g.addEdge(1,0)

Fråga AI

expand
ChatGPT

Fråga vad du vill eller prova någon av de föreslagna frågorna för att starta vårt samtal

some-alt