The main loop

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:

  1. First, we pop the first node from the queue and choose that as current node of this iteration.
node = queue.pop(0)
  1. 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]
  1. Now we will add neighbours of nodes to the queue:
for neighbour in neighbours:
queue.append(neighbour)
  1. Once the main loop is complete, the visited data structure is returned, which contains all the nodes traversed.
  2. The complete code, with both initialization and the main loop, will be as follows:

Let's look at the exhaustive search traversal pattern for the graph that we defined using BFS. To visit all the nodes, the traversal pattern is shown in the following figure. It can be observed that while executing, it always maintains two data structures:

  • Visited: Contains all the nodes that have been visited
  • Queue: Contains nodes yet to be visited

Here's how the algorithm works:

  1. It starts from the first node, which is the only node, Amin, on level one.
  2. Then, it moves to level two and visits all three nodes Wasim, Nick, and Mike one by one.
  3. After that, it moves to level three and level four, which have only one node each, Imran and Faras.

Once all the nodes have been visited, they are added to the Visited data structure and the iterations stop:

Now, let's try to find a specific person from this graph using BFS. Let's specify the data that we are searching for and observe the results:

Now let's look into the depth-first search algorithm.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
52.15.55.18