Objective: To find a way to reach, there are two ways to achieve.
First: Non-recursive methods .
This method requires a stack structure, which can be used to push the vertices of other unreachable vertices into the stack using STL, keeping the top of the stack at the current vertex.
When there is no vertex around the top of the stack, the vertex pops up, always loops to find the destination or stack empty, if it arrives, the stack midpoint will all print out is a road, if the stack is empty, there is no way to reach the destination.
1000001000
0100101000
0101101000
1000001100
0110101000
1010010000
0101000000
0100111000
0010001100
0001100111
Map, ' 1 ' means up to, ' 0 ' means unreachable, but need to first add a layer of unreachable points around the diagram, in order to avoid checking the subscript out of bounds, if you do not want to change the map, but also a sign matrix Flagmap
1 intStackrealize (Const intRowConst intCol)2 {3 while(!Ps.empty ()) {4Point cur =ps.top ();5 intFlag =0;6 for(intI=0;i<8; i++){7Point P = cur+Dir[i];8 if(!flagmap[p.x][p.y] && map[p.x][p.y]=='1'){9Flag =1;TenCur=p; OneFLAGMAP[P.X][P.Y] =1; A Ps.push (cur); - if(Cur.x==row && cur.y==Col) { -cout<<ps<<Endl; the return 1; - } - Break; - } + } - if(!flag) Ps.pop (); + } A return 0; at}
Here point is a struct type:
1 struct point{ 2 int X, Y, 3 point () {}; 4 Point (int xx,int yy) {x=xx;y=YY;}; 5 point (point P) { 6 return point (x+p.x, Y+p.y); 7 8 }WAY[MAXN*MAXN];
Analysis: The last remaining in the stack is up to the target point.
The second type: Recursive method.
Relatively simple, direct stick code:
1 intBFS (Point &cur,Const intRowConst intCol)2 {3 if(Cur.x==row && cur.y==Col) {4Way[len] =cur;5 return 1;6 }7 intFlag =0;8 for(intI=0;i<8; i++){9Point tem = cur +Dir[i];Ten if(flagmap[tem.x][tem.y]==0&& map[tem.x][tem.y]=='1'){ OneFlag =1; AFLAGMAP[TEM.X][TEM.Y] =1; -)if(BFS (Tem,row,col)) way[len++] =tem; - Break; the } - } - returnFlag; -}
Note that to print the path, the recursive function takes a return flag, meaning that if the point is finally on the way to print, it returns 1, otherwise 0 (you can look at the map to simulate it).
Maze Pathfinder Problem