June 2020
Intermediate to advanced
382 pages
11h 39m
English
Next, we will implement the main loop. It will keep on looping until there isn't even a single element in the queue. For each node in the queue, if it has already been visited, then it visits its neighbor.
We can implement this main loop in Python as follows:
First, we pop the first node from the queue and choose that as current node of this iteration.
node = queue.pop(0)
Then, we check that the node is not in the visited list. If it is not, we add it to the list of visited nodes and use neighbors to represent its directly connected nodes
visited.append(node) neighbours = graph[node]
Now we will add neighbours of nodes to the queue:
for neighbour in neighbours: queue.append(neighbour)
Once the main loop is complete, ...