Title description:
The shortest path-finding step of two-dimensional array map
(Subscript starts from 1)
0 0 1 0
0 0 0 0
0 0 1 0
0 1 0 0
0 0 0 1
Such a 4 * 5 matrix, 1 represents a roadblock, 0 can go, starting from (1,1), to the position of (4,3) *** The answer should be 7. There are two ways of walking .
- BFS approach --- BFS uses hierarchical traversal, so the number of layers when traversing to the end for the first time is the shortest number of steps.
1 #include <bits / stdc ++. H> 2 using namespace std; 3 struct Point { 4 int x, y; // Coordinate 5 int step; // Record the number of steps from the initial point to each point 6 Point ( int c, int d, int s): x (c), y (d), step (s) {} 7 }; 8 const int maxn = 20 ; 9 int start_x, start_y, end_x, end_y; 10 int m, n, cnt ; 11 bool inqueue [maxn] [maxn] = { false}; 12 int map_ [maxn] [maxn] = { 0 }; 13 int next [ 4 ] [ 2 ] = { 0 , 1 , 0 , -1 , 1 , 0 , -1 , 0 }; 14 void BFS ( int x, int y) { 15 queue <Point> Q; 16 Q.push (Point (x, y, 0 )); // press the initial point 17 inqueue [x] [y] = true ; // mark in Over team 18 while(!Q.empty()){ 19 Point top=Q.front(); 20 Q.pop(); 21 if(top.x==end_x&&top.y==end_y){//边界 22 cnt=top.step; 23 return; 24 } 25 for(int i=0;i<4;i++){ 26 int tx=top.x+next[i][0]; 27 int ty=top.y+next[i][1]; 28 if(tx<1||ty<1||tx>m||ty>n||inqueue[tx][ty]==true||map_[tx][ty]==1) 29 continue;//剪枝 30 inqueue[tx][ty]=true; 31 Point mid=Point(tx,ty,top.step+1); 32 Q.push(mid); 33 } 34 } 35 } 36 int main(){ 37 while(cin>>m>>n){ 38 cnt=0; 39 memset(inqueue,false,sizeof(inqueue)); 40 memset(map_,false,sizeof(map_)); 41 for(int i=1;i<=m;i++){ 42 for(int j=1;j<=n;j++){ 43 cin>>map_[i][j]; 44 } 45 } 46 cin>>start_x>>start_y>>end_x>>end_y; 47 Point start=Point(start_x,start_y,0);//初始化起始点 48 BFS(start.x,start.y); 49 cout<<cnt<<endl; 50 } 51 return 0; 52 }
DFS practices
1 #include<bits/stdc++.h> 2 using namespace std; 3 int m,n,start_x,start_y,end_x,end_y,cnt,min_step=1000; 4 const int maxn=20; 5 int map_[maxn][maxn]; 6 bool visit[maxn][maxn]; 7 int next[4][2]={0,1,0,-1,1,0,-1,0}; 8 void DFS(int x,int y,int step){ 9 if(x==end_x&&y==end_y){ 10 if(step<min_step) 11 min_step=step; 12 return; 13 } 14 for(int i=0;i<4;i++){ 15 int tx=x+next[i][0]; 16 int ty=y+next[i][1]; 17 if(tx<1||ty<1||tx>m||ty>n||visit[tx][ty]==true||map_[tx][ty]==1) continue; 18 visit[tx][ty]=true; 19 DFS(tx,ty,step+1); 20 visit[tx][ty]=false; 21 } 22 } 23 int main(){ 24 while(cin>>m>>n){ 25 min_step=1000; 26 memset(visit,false,sizeof(visit)); 27 memset(map_,0,sizeof(visit)); 28 for(int i=1;i<=m;i++){ 29 for(int j=1;j<=n;j++){ 30 cin>>map_[i][j]; 31 } 32 } 33 cin>>start_x>>start_y>>end_x>>end_y; 34 visit[start_x][start_y]=true; 35 DFS(start_x,start_y,0); 36 37 cout<<min_step<<endl; 38 } 39 return 0; 40 }