1. Breadth-first search (search for the shortest path)
The shortest route to a friend's house? Win the least number of steps in chess? The closest photographer in the network?
The last 3 steps from Twin Peaks to Golden Gate Bridge.
Second, the concept of graphs: nodes and edges
3. Is there a path? Which path is the shortest?
social network:
In the execution of breadth-first search, the search range gradually extends outward from the starting point, that is, the first-degree relationship is checked first, and then the second-degree relationship is checked. And added to the queue in order.
In other words, the first-level relationship enters the queue first, and the second-level relationship enters the queue later, but the order of the same level can be arranged at will. But avoid duplication.
Four, algorithm implementation
1. Create a queue to store the people to be checked (level 1);
2. Pop a person from the queue and check whether it meets the conditions;
3. Meet, you are done, and quit;
4. If not, add all the neighbors of this person to the queue (second level);
5. Go back to step 2;
6. If the queue is empty, there are no qualified people in your network.
1 from collections import deque 2 3 graph = {} 4 graph["you"] = ["alice","bob","claire"] 5 graph["alice"] = ["peggy"] 6 graph["bob"] = ["anuj","peggy"] 7 graph["claire"] = ["thom","jonny"] 8 graph["anuj"] = [] 9 graph["peggy"] = [] 10 graph["thom"] = [] 11 graph["jonny"] = [] 12 13 def search(name): Create a queue# search_queue = deque () 14 15 search_queue Graph + = [name] # added to your neighbor search queue 16 searched = [] # for recording the inspected person . 17 18 is the while search_queue: # as long as the queue is not empty . 19 Person = search_queue.popleft () # Take the first a person 20 iF not the person in searched: # only when this has not been inspected when the check 21 iF person_is_seller (the person): # check compliance with requirements of 22 Print (the person, " iS a Mango Seller! " ) 23 return True 24- the else : 25 search_queue + = Graph [the Person] # does not meet the requirements, these individual friends to join the search queue 26 searched.append (the Person) 27 return False 28 29 DEF person_is_seller (name): 30 return name [- . 1] == " m " # condition if it is the last letter in the name of m 31 is 32 Search ( " you " )
thom is a mango seller! Out[5]: True
The judged ones should be recorded and not checked next time, otherwise they will fall into an endless loop.
The running time of breadth-first search is O (number of vertices + number of edges) = O (V + E)
note:
1. You need to check the people in the search list in the order of joining, otherwise the found is not the shortest path, so the search list must be a queue.
2. For those who have checked, don't check again, otherwise it may cause an endless loop.