The shortest path to another point (end point), the shortest distance;
The points in the figure are represented as heights of different elevations in the graph, which cannot be passed; a point with no number indicates an elevation of 0, which can be passed by the ground;
This is a typical two-point shortest path in the graph, and in this case, the depth-first algorithm is used to achieve it;
There are four directions at each point (some of the points do not pass in some direction), so at each point there are four directions to be handled;
How is the depth-first algorithm function written?
That is, write the recursive function ... But the recursive function is swollen to write???
First: Judging the initial state, starting from the starting point, just start the number of steps for 0;dfs (start_x, start_y, 0);
Second: Starting from the beginning, what to do? Try a four-way walk.
What do you want in each direction? First judge whether this point reaches the boundary, and then judge whether the point has passed and whether it is high ground, if it is not high ground and did not pass, then from that point, do the same thing as the previous point;
DFS (TX, Ty, step+1);
Second: Judge the termination condition, reach the end point, judge the current steps; return;
/*************************************************************************> File name:search_min_step.cpp> Author: > Mail: > Created time:2015 November 13 Friday 21:49 41 seconds ******************************************************* /#include <iostream>using namespace std;const int max_x = 50;const int max_y = 50;int Min_step = 100 00;int my_x, My_y;int map[max_x][max_y];int book[max_x][max_y];int start_x, Start_y;int dest_x, dest_y;void dfs (int x, in T y, int step) {/*up, right, down, left*/int next[4][2] = {{0,-1}, {1, 0}, {0, 1}, {-1, 0}}; int TX, Ty; if (x = = dest_x && y = = dest_y) {if (Step < min_step) Min_step = step; Return } for (int i = 0; i < 4; i++) {tx = x + next[i][0]; ty = y + next[i][1]; if (tx > My_x | | ty > MY_Y | | tx < 0 | | Ty < 0) continue; if (map[tx][ty] = = 0 && book[tx][ty] = = 0) {Book[tx][ty] = 1; DFS (TX, Ty, step+1); Book[tx][ty] = 0; }}}void Input_map_info () {cout << "input the max x:"; Cin >> my_x; cout << "input the max y:"; Cin >> my_y; cout << "Input the map information:\n"; for (int i = 1, i <= my_x; i++) {for (int j = 1; J <= My_y; j + +) {cin >> map[i][j]; }}}int Main () {input_map_info (); cout << "Input the source location:"; CIN >> start_x >> start_y; cout << "Input the Destat location:"; CIN >> dest_x >> dest_y; Book[start_x][start_y] = 1; DFS (start_x, start_y, 0); cout << "min_step =" << min_step << Endl; return 0;}
Finding the shortest path-----depth First algorithm C + + implementation in the graph