Understanding breadth-first search

Source: Internet
Author: User

Some time ago I encountered some interesting questions related to BFS. I thought about it with the help of some friends or materials and found that if this simple algorithm can be used freely, it is indeed able to play a powerful role, so I wrote a blog record.

The concept of BFS is very simple. Here we will introduce it. BFS implementation is also very simple. You can use a queue. It is indeed a very important algorithm in the figure, it can also be used to solve problems that seem to have no obvious relationship with the graph. The key to understanding the breadth-first search is to understand its application.

1. Basic Applications

The breadth-first search algorithm is defined based on graphs. Therefore, the most intuitive application is naturally shown in the figure: vertex and edge.

For example, if a map is vertex, and the path connecting two locations is edge, it is assumed that the edge length is the same (of course, this is actually impossible ), we can use the breadth-first search to obtain the shortest distance between two points;
For example, in interpersonal relationships, a person is vertex, and whether or not the two know (connected) is edge. We know kaixin.com, and LinkedIn is like this, in this case, we should be able to use the breadth-first search to get at least a few friends between two people. It is said that we can get to know the President through six people-not too bad.

However, there are many problems that are not so intuitive. You may not see a picture or the applicability of BFS. At this point, we need enough insight to abstract the problem to a graph and select the correct target function to apply BFS. The following examples are described respectively.

2. Maze Problems

The maze is composed of square grids, some of which are interconnected, and some are not. Put a mouse in such a maze and ask the mouse how to get out of the maze as quickly as possible.

Here, the maze can be represented by a simple two-dimensional array. The element value of the array 1 indicates connectivity, and the value of 0 indicates non-connectivity. Although this is not a direct graph problem, it is not difficult to see its relevance with the graph:

Vertex: All cells with a value of 1. (The lattice with a value of 0 does not belong to this graph logically because it is not connected, but we rely on it to determine whether edge exists between two points)
Edge: the relationship between any two adjacent vertex with a value of 1

It can be found that this form of expression of graphs in the maze is very different (more compact) from that in the traditional adjacent table, but it is very suitable for representing a structure like the maze. This is also a graph, but it only has a specific access method. Specify the start point and end point (any border vertex ),
Apply BFS to this array to find the shortest path for getting out of the maze. Of course, you must note that you cannot repeatedly access the accessed nodes. You can directly modify the array representing the maze, if it is set to 0 after the access, you can also provide an auxiliary array to mark whether the access is successful.

Here is an article detailing the solution to the Maze problem.

3. Liquor Problem

An 8L cup is full of wine, with a 3L empty cup and a 5L empty cup. Ask how to use the minimum number of times to pour the 4L wine. (Cannot be reversed)

This is a common logic question in the interview. If you don't know the routine behind it, you just keep trying like a fly, in this case, it may take a lot of time, and it may not necessarily be the least. Even, it may also confuse yourself.

One solution is to regard the number of wines in the last three cups as one State, while the "Inverted" process is a State migration process with the initial state of 800, the status migration requires that the wine of cup A be poured into cup B, and the result must be either A is empty or B is full. We can have the following reasoning process:

Pay attention to the following two points for this reasoning process:

  • First, I adopted the "width first" State migration process, that is to say, my thought process is from left to right, and then in each column from top to bottom, this ensures that I find the minimum number of steps.
  • Second, I will not deal with the status that has already appeared, or the scale of the problem will not be gradually reduced (for example, after 800 to 530, it is natural that when we expand 530, I can switch back to 800, but because 800 has appeared, it will not be processed)

Here, the route 800-305-332-602-620-125-134 is one-step ahead!

As you can see, here is actually the application of the breadth-first search algorithm, for more complex problems (such as five cups), can be programmed to solve. So where is the graph?
Vertex: the State of the wine in three cups at a certain time.
Edge: You can migrate from one status to another through a single pour.

To identify whether a status has been accessed, we can use an array of 1000 characters. The default value is 0, and the status value at a time point is an array subscript, that is, 100 * a + 10 * B + c. (Think, what if the capacity of a cup is greater than 10 ?)

(Thanks to atyuwen for providing this idea)

With this idea, it is easier to solve the following bridge problem:

Four women bridge, there is a torch at night, each time up to two, must carry a torch, bridge speed is not the same 1 min, 2 min, 5 min, 10 min; two people use the slowest speed, fire cannot be thrown. How can four women bridge the bridge in the shortest time?

This problem can be solved through thinking. The principle is to try to bring people who are fast and slow together to avoid being dragged down by slow people quickly (similar to multi-thread load balancing ), the solution is as follows:

  • 1, 2 in the past 1 back: 3
  • 5, 10 back in the past 2: 12
  • 1, 2 past: 2

17 minutes, but if there are many people, you may not be sure whether it is the fastest. This problem can also be solved using the BFS algorithm of the figure:
Vertex: the state of the person on the opposite side. It can be represented by a four-digit binary number. If no one matches the state of a person respectively, 0000 indicates that one person has not passed, and 1111 indicates that all people have passed.
Edge"

In this way, the algorithm should not be difficult to come out.

4. continuous playback

This is actually an algorithm introduced in chapter 1 "1.14 connected game design" of the beauty of programming. The value of the array element represents different graphics, we can use 0 to indicate that there is no image at this position. The two nodes can be connected in a link view to eliminate the following standard: the same image with no more than two bends connected:
 

(Picture taken from the beauty of programming)

The structure of this problem is a bit similar to that of the maze. However, in order to apply BFS, our brain has to be bent. After the Players click two nodes in sequence, we need to determine whether the problem can be eliminated:

  • It is very easy to determine whether the image is equal. You only need to determine the value of the element.
  • Whether the connection has no more than two bends, we need to take A node as the starting point, first get the node set A that can be reached without turning, to see if the target node is inside; if not, you need to set all nodes in node A to get the nodes that can be reached without turning (not accessed before) and determine whether the target node is included. If not, continue to expand, if the connection is no longer available this time, it indicates that the connection between the two nodes has exceeded two bends and is not satisfied.

Vertex is the connection between all nodes without graphs, while edge is any two nodes in the same straight line that are not truncated by any graph node. BFS is applied because the distance between nodes is no more than two times. Here the distance refers to the number of turns.

Through appeal examples, the strength and fun of BFS can be seen!

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.