N*m Maze, from the starting point to the end, to find the shortest distance
The width-first search is searched in the order of from near from the start state, so it can be easily used to find answers to the shortest path, minimum operations, and so on. (can be constructed as pair or encoded into int to express state)
When the state is more complex, it needs to be encapsulated into a class to represent the state.
Although the search stops when you reach the end, you can calculate the shortest distance from each location if you continue until the queue is empty. In addition, if the search Finally, D is still the INF, you can know that this location is unable to reach from the beginning of the location.
1 Const intINF =100000000;2 3typedef pair<int,int> P;//Using a typedef is more convenient when using the pair to represent states.4 5 Charmaze[max_n][max_m+1];//an array of strings that represent mazes6 intn,m;7 intSx,sy;//Start coordinates8 intGx,gy;//End coordinates9 Ten intd[max_n][max_m+1];//an array of strings that represent mazes One A intdx[4]={1,0,-1,0};//Vector moving in 4 directions - intdy[4]={0,1,0,-1}; - the - //to find the shortest distance from (Sx,sy) to (gx,gy) - //if unreachable, it is the INF - intBFS () + { -Queue<p>que; + //initialize all positions to INF A for(intI=0; i<n; i++){ at for(intj=0; j<m; J + +){ -D[i][j]=inf;//Add the starting point to the queue and set the distance of this location to 0 - } - } - Que.push (P (Sx,sy)); -d[sx][sy]=0; in - //keep looping until the queue length is 0 to while(Que.size ()) { + //remove elements from the front of the queue -p=Que.front (); the Que.pop (); * //if the removed state is already an end, the search ends $ if(P.FIRST==GX && p.second==gy)Panax Notoginseng Break; - //Four Directions the for(intI=0; i<4; i++){ + intnx=p.first+Dx[i]; A intNy=p.second+Dy[i]; the //determine if it can be moved and whether it has been accessed (D[nx][ny]!=inf is already visited) + if(0<=nx && nx<n &&0<=ny && ny<m && maze[nx][ny]!='#'&& d[nx][ny]==INF) { - //if it can be moved, it is added to the queue, and the distance to the position is determined as the distance to P +1 $ Que.push (P (Nx,ny)); $d[nx][ny]=d[p.first][p.second]+1; - } - } the } - returnD[gx][gy];Wuyi } the - voidsolve () { Wu intans=BFS (); -printf"%d\n", ans); About}
Shortest path to the maze (BFS)