Breadth-First search (BFS) (with examples) questions arise:
Isenbaev is a foreign Daniel.
Now there are many people who want to take part in ACM ICPC.
There are altogether n groups, each group of 3 persons. All 3 people in the same group are teammates.
Everyone wants to know what the minimum distance is from Daniel.
Daniel's minimum distance with himself is of course 0. The minimum distance between Daniel's teammates and Daniel is 1. Daniel's teammate's teammates and Daniel's minimum distance is 2 ... And so on
If the real and Daniel has no relationship with the output undefined.
The first line reads N. Represents a group of N. 1≤n≤100
Next n lines, each row has 3 names, and the names are separated by a space. The beginning of each name is capitalized.
Each row outputs a name followed by a space after which the output number A or string undefined,a represents the minimum distance.
The name is output in dictionary order.
Sample Input7233undefined21023undefined1undefined21
Problem analysis
The way to solve this problem is to use breadth-first search. So we first put forward the knowledge point analysis of breadth-first search.
Breadth First Search
Knowledge points from: breadth/Breadth First search (BFS)
1. Preface
Breadth-First search (also known as width-First search, abbreviated BFS, described by breadth below) is a traversal strategy for connected graphs. Because its idea is to start from a vertex V0, radiating the priority to traverse its wider area around, so named.
What do you usually do with it? One of the most intuitive classic examples is to go to the maze, we start from the beginning, to find the shortest distance to the end, many of the shortest path algorithm is based on the idea of breadth first established.
The introduction of the algorithm will give a lot of strict proof, I want to write as much as possible, so the use of some intuitive to disguise as proof, the key point can help you get to the good.
2. The concept of graphs
Just said the breadth-first search is a traversal strategy for connected graphs, so it is necessary to explain the diagram briefly first.
2-1, this is what we call the connected graph, shown here is an undirected graph, connected that every 2 points have at least one path connected, such as V0 to V4 path is v0->v1->v4.
In general, we use the V abbreviation for the vertex, and the edge with the e abbreviation.
3. Basic Ideas
Often we have such a problem, starting from a starting point to an end point, we want to find a shortest path, from figure 2-1, if we ask V0 to V6 a shortest path (assuming a node in one step to calculate) "Note: Here you can choose not to look at this text directly see Figure 3-1", We see clearly that this path is v0->v2->v6, not v0->v3->v5->v6. First think about how you have just found this path: First look at the node with V0 directly connected V1, V2, V3, found no V6, and then see just V1, V2, V3 Direct connection nodes are: {V0, V4}, {V0, V1, V6}, {V0, V1, V5} (The strikethrough here means that the vertices have been searched during our search, and we don't have to look back and see them again). At this time we found the V6 from V2 's connected node set, which means we found the shortest path to the V0 to V6: V0->v2->v6, although you will find another path V5 after you search the V0->V3->V5->V6 connection node collection further, But obviously he is not the shortest path.
You're going to see a little bit like the radiation shape of the search method, from a node, to its next node to pass the virus, so that a layer of transmission radiation down, know that the target node is radiated, at this time has been found from the starting point to the end of the path.
We use the example diagram to illustrate this process, in the process of the search, the initial all the nodes are white (representing all the points have not yet begun to search), the starting point V0 sign Gray (indicating the impending radiation V0), the next search, we put all the gray nodes visited once, Then turn it into black (indicating that it has been radiated), and then mark the nodes they can reach in gray (because those nodes are the target points for the next search), but here's a judgment, like in the case of the V1 node, where the next node should be V0 and V4, But V0 has been dyed black in the front, so it will not be dyed grey. This continues until the target node V6 is dyed gray, indicating that the next step to the end, there is no need to search (dyeing) Other nodes, at this time can end the search, the entire search is over. Then according to the search process, in turn, the shortest path to find out, figure 3-1, the final path on the node marked green.
The whole process is as follows:
4 Flowchart for Search
5 Simple examples
The Maze problem
Define a two-dimensional array:
int maze[5][5] = { 0, 1, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 0,};
It represents a maze, of which 1 represents a wall, 0 means that the road can be walked, can only walk sideways or vertical walk, can not be inclined to walk, asked to compile the program to find the shortest route from the upper left to the lower right corner.
The topic guarantees that the input is a definite solution.
Perhaps you would ask, how does this map with breadth-first search? The first step of BFS is to identify the node and edge of the graph!
5.1 Identifying the edges of a node
A node is a state, and an edge is a rule between a node and a node.
Corresponding to the maze problem, you can think that the node is the maze of every lattice (not the wall), when the maze, the relationship between the lattice? According to the meaning of the topic, we can only walk, so we could see that the lattice and its vertical and horizontal lattice is connected, as long as this lattice with another lattice is connected, then two lattice nodes have a side.
If the subject is changed into oblique direction can also go, then the lattice with the surrounding 8 lattice can be connected, so a node will have 8 sides (except the boundary node).
5.2 Ideas for solving problems
The input array corresponding to the topic:
0, 1, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 0,
We define the node as (x, y), (x, y) to represent the maze of the array maze[x][y].
So the starting point is (0,0), the end is (+). In the light of the idea, we'll probably hand-comb it again:
Initial:
Beginning vs for (0,0)
End of VD (BIS)
Gray node Collection q={}
Initialize all nodes as white nodes
Start our breadth search!
Manually perform the steps "PS: You can look directly at Figure 4-1":
1.Start node vs turn Gray, join queue q,q={(0,0)}2.Remove the first node of the queue Q vn,vn={0,0}, q={}3.Put vn={0,0}Dyed black, remove all adjacent white nodes of VN{(1,0)}4.Does not contain an end point (4,4), dyed gray, joins the queue q,q={(1,0)}5.Remove the first node of the queue Q vn,vn={1,0}, q={}6.Put vn={1,0}Dyed black, remove all adjacent white nodes of VN{(2,0)}7.Does not contain an end point (4,4), dyed gray, joins the queue q,q={(2,0)}8.Remove the first node of the queue Q vn,vn={2,0}, q={}9.Put vn={2,0}Dyed black, remove all adjacent white nodes of VN{(2,1), (3,0)}.Does not contain an end point (4,4), dyed gray, joins the queue q,q={(2,1), (3,0)}One by one .Remove the first node of the queue Q vn,vn={2,1}, q={(3,0)}.Put vn={2,1}Dyed black, remove all adjacent white nodes of VN{(2,2)}.Does not contain an end point (4,4), dyed gray, joins the queue q,q={(3,0), (2,2)}.Continued, knowing that all the adjacent white nodes of the VN were contained (4,4)......A .Now you get the answer.
Start you can easily imitate the top process to reach the end, then why is it the shortest?
How do you guarantee it?
Let's take a look at the sequence of nodes in the breadth search process:
Do you see what the order of breadth search looks like?
The label is the order of our search process, we observed that this search order is based on the hierarchical relationship, such as node (0,0) in the 1th Layer, node (1,0) in the 2nd Layer, node (2,0) in the 3rd Layer, node (2,1) and Node (3,0) in the 3rd layer.
Our search order is the first layer, the second layer, the third layer, and the nth layer.
We assume that the end point is in the nth layer, so the path length we search for is definitely n, and this n must be the shortest.
We use a simple method of proving that the end point appears above the nth layer, such as the first M layer, m
5.3 Core Code
/** * Breadth First search * @param Vs start * @param Vd End */ BOOLBFS (node& Vs, node& Vd) { queue<Node>Q; Node Vn, Vw;intI//Initial state puts the starting point in the queue QQ.push (Vs); Hash (Vw) =true;//Settings node has been visited! while(! Q.empty ()) {//queue is not empty, continue searching! //Remove the head of the queue vnVn = Q.front ();//Remove from queueQ.pop (); while(Vw = the node to which the VN is reachable by a certain rule) {if(Vw = = Vd) {//Find the end! //To record the path, no solution is given here return true;//Return}if(IsValid (VW) &&!VISIT[VW]) {//VW is a legitimate node and is a white nodeQ.push (VW);//Join queue QHash (Vw) =true;//Set node color} } }return false;//No solution}
Problem solving
For this problem, first we bind each string name to a numeric number, which is used to store their corresponding distances in an array. The node is the first part of the map, and the edge is the individual string within the same 3-dimensional array.
#include <cstdio>#include <cstring>#include <algorithm>#include <iostream>#include <map>#include <string>#include <queue>using namespace STD; Map<string, int>hh Map<string, int>:: Iterator it; Queue<int>QuestringStrstrings[ the][4];intdis[11000];intMain () {str ="Isenbaev";intNscanf("%d", &n);inttot =0;//tot is actually the number of each name. for(inti =1; I <= N; i++) { for(intj =1; J <=3; J + +) {Cin>> S[i][j];if(Hh.find (s[i][j]) = = Hh.end ()) {Hh[s[i][j]] = ++tot; } } }BOOLFlag =false; for(inti =1; I <= N; i++) { for(intj =1; J <=3; J + +) {if(S[i][j] = = str) {flag =true; Break; } } }//If STR is not found, all are undefined if(!flag) { for(it = Hh.begin (); It! = Hh.end (); it++)cout<< It->first <<"undefined\n";return 0; } while(!que.empty ()) Que.pop ();//Empty queueQue.push (Hh[str]);//Put the STR number into the queue header memset(Dis,-1,sizeof(dis));//Set all dis to-1DIS[HH[STR]] =0;//STR dis is 0 while(!que.empty ()) {//When Que is empty, the description has ended the search. intx = Que.front ();//Output headQue.pop (); for(inti =1; I <= N; i++) for(intj =1; J <=3; J + +) {intid = hh[s[i][j]];//In order to find the head number of dis if(id! = x)Continue; for(intK =1; K <=3; k++) {intnum = hh[s[i][k]];if(Dis[num] = =-1) {Dis[num] = dis[x]+1; Que.push (num); } } } } for(it = Hh.begin (); It! = Hh.end (); it++) {cout<< It->first <<" ";if(Dis[it->second] = =-1)cout<<"undefined"<<"\ n";Else cout<< Dis[it->second] <<"\ n"; }}
[C + +] breadth-First search (BFS) (with examples)