Software Environment: Python 3.7.0B4
First, the algorithm description
Suppose you run a mango farm and need to find a mango dealer to sell the mango to him. For this reason, we can find the eligible mango sellers in our friends by breadth-first search algorithm.
Breadth-First search is a look-up algorithm for graphs that can help us answer two types of questions:
- First type of question: From Node A, is there a path to Node B? (Are there any mango sellers in your network?) )
- Second type of question: From Node A, which path to Node B is the shortest? (Which Mango dealer has a recent relationship with you?) )
Second, the realization diagram
The following diagram is implemented with a hash table
Graph ={}graph[" You"] = ["Alice","Bob","Claire"]graph["Bob"] = ["Anuj","Peggy"]graph["Alice"] = ["Peggy"]graph["Claire"] = ["Thom","Jonny"]graph["Anuj"] =[]graph["Peggy"] =[]graph["Thom"] =[]graph["Jonny"] = []
Note: Anuj, Peggy, Thom, and Jonny have no neighbors, because although there are arrows pointing to them, there are no arrows from them pointing to others. This is called a directed graph, where the relationship is unidirectional. The undirected graph has no arrows, and the nodes connected directly to each other are neighbors.
Third, the realization algorithm
Overview of how breadth-first search algorithms work:
The complete implementation code is as follows:
fromCollectionsImportdequedefPerson_is_seller (name):returnNAME[-1] = ='m'Graph={}graph[" You"] = ["Alice","Bob","Claire"]graph["Bob"] = ["Anuj","Peggy"]graph["Alice"] = ["Peggy"]graph["Claire"] = ["Thom","Jonny"]graph["Anuj"] =[]graph["Peggy"] =[]graph["Thom"] =[]graph["Jonny"] = []defSearch (name): Search_queue= Deque ()#Create a queueSearch_queue + = Graph[name]#Add your neighbors to this search queuesearched = []#This array is used to record people who have been checked whileSearch_queue:#as long as the queue is not emptyperson = Search_queue.popleft ()#Take out the first one of them. if notPersoninchSearched:#only if the person doesn't check out the old one. ifPerson_is_seller (person):#Check if this person is a mango dealer. Print(Person +"Is a mango seller!") #It's a mango dealer . returnTrueElse: Search_queue+ = Graph[person]#not a mango dealer. Add this person's friends to the search queueSearched.append (person)#mark this person as checked. returnFalse#no one in the queue is a mango dealer.Search (" You")
Iv. Summary
- The queue is FIFO.
- The stack is last-in-first-out.
- You need to check people in the search list in order, otherwise the shortest path is not found, so the search list must be a queue.
- For those who have checked, be sure not to check again, otherwise it may lead to an infinite loop.
The sixth chapter of the algorithm diagram notes