python-Breadth First Search

Source: Internet
Author: User

Breadth First Search

Here we come to the BFS algorithm strategy:

 

For example: What is the shortest route from the Twin Peaks----> Golden Gate Bridge?

We use breadth-first search to solve the problem, note that the key to breadth-first search lies in the "wide", that is to say, the Twin Peaks as the starting point, we should as much as possible to compare with the neighboring path, from which to choose an optimal path.

The first step:

  

After exploring point A and point B along the two arrow paths, we found that we didn't get to where we wanted to go, so I went on exploring.

  

Again, we find that we have not reached our destination and continue to explore.

  

Upon arriving at this step, we found that one of the paths had reached the Golden Gate Bridge, while the other two routes reached point C only. Therefore, we find the shortest path is: Gemini Peak->a->c-> Golden Gate Bridge.

So, from the above we can know that breadth-first search is actually a way to explore the shortest path.

Based on the above example, we want to find a shortest path to a place, which requires a two-step process:

(1) Use the diagram to establish the problem model.

(2) Use breadth-first search to solve problems.

Using breadth-first search, we can answer two questions:

1. From Node A, do you have a path to the B node?

2. From Node A, which path to the B node is the shortest one?

First, let's take a look at how to build a picture.

Here we will use a data structure---hash table that can represent the mapping relationship. As for what is a hash table, we will not repeat it here.

For example:

    

Graph = {}

grapu[' you '] = [' Alice ', ' Bob ', ' Mar ', ' rain ', ' cat ']

Here the "You" is mapped to an array. Inside this array of ' You ', contains all the elements that are adjacent to you.

With this approach, we can build a bigger picture.

Algorithm implementation strategy:

    

First, create a double-ended queue that will need to be found in the push-in queue.

From collections Import Deque

def person_is_seller (name):

return name[-1] = = ' m ' #如果这个名字是以M结尾, it is

Graph = {}

grapu[' you '] = [' Alice ', ' Bob ', ' Mar ', ' rain ', ' cat ']

Search_queue = deque () #创建一个队列

Search_queue + = graph[' You '] #将you压入队列

While Search_queue: #只要队列不为空

person = Search_queue.popleft () #取出左边第一个人

If Person_is_seller (person): #检查这个人是否为芒果商

Print person + = ' is a mango seller! ‘

Return True

Else

Search_queue + = Graph[person] #将这个人的朋友加入队列

return False #没有芒果商

However, the above algorithm has an obvious problem, if your friend Alice and Bob have this friend, then in the process of searching will be caught in a loop state. To solve this problem, we can set up a list to mark those who have been looked up. So the final code is as follows:

def search (name):

Search_queue = deque () #创建一个队列

Search_queue + = Graph[name] #将需要查找的压入队列

Searcher = [] # is used to record an already-searched

While Search_queue: #只要队列不为空

person = Search_queue.popleft () #取出左边第一个人

If not searched: #当这个人不在searched中才继续往下查找

If Person_is_seller (person): #检查这个人是否为芒果商

Print person + = ' is a mango seller! ‘

Return True

Else

Search_queue + = Graph[person] #将这个人的朋友加入队列

Searched.append (person)

return False #没有芒果商

Performance Analysis:

First look along each edge, if the number of edges is n, the lookup efficiency is O (V)

Again, we need to make two judgments about the list that we have searched for each time we look for it.

Therefore, the total search efficiency for breadth-first searches is O (v+n)

  

python-Breadth First Search

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.