Blue Bridge Cup Selected Questions Algorithm Series - Global Warming - BFS

This column has been included .
Let's take an example to understand the principle of BFS:
Take a mouse walking in a maze as an example. The road in the maze is intricate and complicated. After the mouse enters from the entrance, how can the mouse find the exit?
BFS: A group of mice walks a maze. Assuming that there are infinitely many rats, after this group of rats enters, at each intersection, some rats are sent to explore all the untraveled roads. A rat walking on a certain road, if it hits a wall and cannot move forward, stops; if the intersection it reaches has already been explored by other rats, it also stops. Obviously, all roads will be followed and not repeated until the exit is encountered. This idea is BFS.
In specific programming, the data structure of queue is generally used to implement BFS, that is, "BFS = queue"; while DFS is generally implemented by recursion, that is, "DFS = recursion".
Let's now further compare BFS and DFS to gain an in-depth understanding of BFS: I learned about DFS
in the previous lecture . Do you think DFS is a dead end? Regarding the question of "a mouse walks the maze", the steps of DFS are "go all the way to the end until it hits a wall; when it hits a wall, go back to the previous step, change the intersection and continue all the way to the end until it hits a wall...". It doesn't care whether the current step will lead to a dead end, or take a long detour. For example, in the picture below, "@" is the starting point, "*" is the ending point, "#" is the wall that cannot be walked, and the black dot is the next intersection that can be walked, you can only walk up, down, left and right. Figure 1 A maze diagram


Figure 1 A maze diagram

Then, to find the way from the starting point to the ending point, assuming that at each step, you follow the method of first left and then right, then the DFS result will be like this:
Please add image description
Figure 1 DFS A path from "@" to "*"

It was a road that could be reached in two steps, but he took 13 steps.

But the mice who can BFS are not so clumsy. It is much smarter, it "sees all directions" in every position, tries every possible way to go next, and then continues the road behind. So how will it go? Look at the picture below: Please add image description
Figure 3 BFS finds the path from "@" to "*"
So the route of this smart mouse is:
1. Start from point 1.
2. Walk to all two neighbors 2,3 of 1. At this time, the two points (2, 3) that are one step away from the starting point 1 have been reached.
3. Continue on to the neighbors of 2 and 3. For convenience, let it come in order: go all neighbors of 2 first, (4, 5, 6) go.
4. Then go to 3's neighbors 7 and 8. At this time, the points (4, 5, 6, 7, 8) two steps away from the starting point 1 have been reached. And met the end point 8, just two steps! Very smart, isn't it? However, in order to show his ability, the mouse decided to continue to reach all the points.
5. Neighbor 9 for 4, 10 for 5, 11 for 6, 12 and 13 for 7. At this time, the points (9, 10, 11, 12, 13) three steps away from the starting point 1 have been reached.
6. Go further, and the points (14, 15) that are four steps away from the starting point 11 are all reached.
Not only that, but the smart mouse also found that the above steps couldn't be easier to do with a queue. Let's fill in a form for it to explain in detail the steps of how to implement BFS with queues. Please add image description
Next let's take a look at some classic problems of BFS.

connectivity issues

Connectivity judgment is a simple problem in graph theory. It is to find the interconnected parts of a graph. It is a basic search. Either DFS or BFS can be used:
BFS Judgment Connectivity Steps:

1. Start traversing from any point u on the graph and put it into the queue.
2. Pop up the queue head u, mark that u has been searched, and then search for u's neighbors. If the neighbors meet the connectivity conditions, put them in the queue.
3. Continue to pop up the head of the queue, mark the searched, and then search for its neighbors, and put those that meet the connectivity conditions into the queue. Continue the above steps until the queue is empty. At this point all connected points have been found.

The steps for DFS to determine connectivity are:

1. Start traversing from any point u on the graph, and mark that u has been searched.
2. Recursively u's neighbors that meet the connectivity condition.
3. The recursion ends and all connected points are found.

Let's take a look at the Blue Bridge Cup real questions related to connectivity!

Topic description

You have a NxN pixel photo of a sea area, "." for ocean and "#" for land, like this:

.##…

.##…

…##.

…####.

…###.

Among them, a piece of land connected in the four directions of "up, down, left and right" forms an island. For example, there are 2 islands in the picture above.

Due to rising sea levels caused by global warming, scientists predict that a pixel of the edge of the island will be submerged by sea water in the next few decades. Specifically, if a land pixel is adjacent to an ocean (there are oceans in four adjacent pixels up, down, left, and right), it will be submerged.

For example, the sea area in the picture above will look like this in the future:

…#…

Please count: According to scientists' predictions, how many islands in the photo will be completely submerged.

enter description

The first line contains an integer N (1≤N≤1000).

The following N rows and N columns represent a photo of a sea area.

The photo guarantees that the pixels in row 1, column 1, row N, and column N are all oceans.

output description

Output an integer representing the answer.

sample input

7
.......
.##....
.##....
....##.
..####.
...###.
.......

Sample output

1

Problem solving ideas:

Apparently it's a connectivity issue. The steps are:

1. Traverse a connected block (find all '#' in this connected block, and mark it as already searched, no need to search again);
2. Traverse the next connected block...;
3. After traversing all connected blocks, count how many a connected block.

def bfs(x,y):
    d = [(0,1),(0,-1),(1,0),(-1,0)]    
    q = [(x,y)]    #用list实现队列    
    vis[x][y]=1
    global flag    
    while q:            
        t=q.pop(0)          
        tx,ty = t[0],t[1]
        if mp[tx][ty+1]=='#' and mp[tx][ty-1]=='#' and \
           mp[tx+1][ty]=='#' and mp[tx-1][ty]=='#':
           flag = 1
        for i in range(4):
            nx = tx+d[i][0]
            ny = ty+d[i][1]
            if vis[nx][ny]==0 and mp[nx][ny]=="#":               
               q.append((nx,ny))                          
               vis[nx][ny]=1

n = int(input())
mp =[]
for i in range(n):
    mp.append(list(input()))
vis = []
for i in range(n):
    vis.append([0]*n)
ans = 0
for i in range(n):
    for j in range(n):
        if vis[i][j]==0 and mp[i][j]=="#":
            flag = 0
            bfs(i,j)
            if flag == 0:
                ans+=1
print(ans)

First, let's interpret the implementation process of this bfs.
The mp list is the land and sea maps we store. The vis list is a judgment list with the same specification as the mp list, which is used to help determine whether the land with "#" has been judged. Reduce program complexity.
Then enter the bfs function, the d list is used to search for a '#' near a land "#", we can call it a direction list.
The q list is used to store the coordinates of the "#" land that has been judged and searched. When the q list does not contain any parameters, we can say that we have traversed a set of lands and their surrounding lands.

Then we have to think about whether the implementation process of BFS in this question is the same as the BFS principle we understood before?
The implementation process in this topic is mainly to traverse the land one by one, and then traverse the land in four directions, up, down, left, and right, and continue to spread around in turn, until all the land is traversed, and the program ends.
And the principle of BFS we mentioned before is not to extend to the end with the operation of the queue.
Then after this question, we need to really learn how BFS is implemented through programming, so we need to practice a few more times for this programming idea:

def bfs(x,y):
    d = [(0,1),(0,-1),(1,0),(-1,0)]    
    q = [(x,y)]    #用list实现队列    
    vis[x][y]=1
    global flag    
    while q:            
        t=q.pop(0)          
        tx,ty = t[0],t[1]
        if mp[tx][ty+1]=='#' and mp[tx][ty-1]=='#' and \
           mp[tx+1][ty]=='#' and mp[tx-1][ty]=='#':
           flag = 1
        for i in range(4):
            nx = tx+d[i][0]
            ny = ty+d[i][1]
            if vis[nx][ny]==0 and mp[nx][ny]=="#":               
               q.append((nx,ny))                          
               vis[nx][ny]=1

Guess you like

Origin blog.csdn.net/m0_51951121/article/details/123300818