经典的迷宫最短路问题,DFS,BFS求解均可,DFS需要注意增加最短距离这个量来最优化剪枝和求解。BFS需要在状态里加入一个当前BFS树的深度。
1 #include<iostream> 2 #include<algorithm> 3 #include<cstdio> 4 #include<climits> 5 #include<vector> 6 #include<queue> 7 using namespace std; 8 struct datatype 9 { 10 int x; 11 int y; 12 }; 13 struct pointtype 14 { 15 int x; 16 int y; 17 int len; 18 vector<datatype> path; 19 }; 20 queue<pointtype> q; 21 bool map[7][7]; 22 bool vis[7][7]; 23 int n=5,m=5; 24 int main() 25 { 26 for(int i=0;i<=n+1;i++) 27 { 28 for(int j=0;j<=m+1;j++) 29 { 30 map[i][j]=false; 31 vis[i][j]=false; 32 } 33 } 34 for(int i=1;i<=n;i++) 35 { 36 for(int j=1;j<=m;j++) 37 { 38 int tmp; 39 scanf("%d",&tmp); 40 if(!tmp) 41 { 42 map[i][j]=true; 43 } 44 } 45 } 46 pointtype now; 47 now.x=1; 48 now.y=1; 49 now.len=1; 50 now.path.clear(); 51 datatype his; 52 his.x=1; 53 his.y=1; 54 now.path.push_back(his); 55 vis[1][1]=false; 56 q.push(now); 57 vector<datatype> res; 58 int res_len=INT_MAX; 59 while(!q.empty()) 60 { 61 now=q.front(); 62 vis[now.x][now.y]=false; 63 if(now.x==n&&now.y==m) 64 { 65 if(res_len>now.len) 66 { 67 res_len=now.len; 68 res=now.path; 69 } 70 break; 71 } 72 else 73 { 74 if(!vis[now.x+1][now.y]&&map[now.x+1][now.y]) 75 { 76 pointtype tmp=now; 77 tmp.x+=1; 78 his.x=tmp.x; 79 his.y=tmp.y; 80 tmp.path.push_back(his); 81 tmp.len+=1; 82 q.push(tmp); 83 } 84 if(!vis[now.x-1][now.y]&&map[now.x-1][now.y]) 85 { 86 pointtype tmp=now; 87 tmp.x-=1; 88 his.x=tmp.x; 89 his.y=tmp.y; 90 tmp.path.push_back(his); 91 tmp.len+=1; 92 q.push(tmp); 93 } 94 if(!vis[now.x][now.y+1]&&map[now.x][now.y+1]) 95 { 96 pointtype tmp=now; 97 tmp.y+=1; 98 his.x=tmp.x; 99 his.y=tmp.y; 100 tmp.path.push_back(his); 101 tmp.len+=1; 102 q.push(tmp); 103 } 104 if(!vis[now.x][now.y-1]&&map[now.x][now.y-1]) 105 { 106 pointtype tmp=now; 107 tmp.y-=1; 108 his.x=tmp.x; 109 his.y=tmp.y; 110 tmp.path.push_back(his); 111 tmp.len+=1; 112 q.push(tmp); 113 } 114 } 115 q.pop(); 116 } 117 vector<datatype>::iterator it; 118 for(it=res.begin();it!=res.end();it++) 119 { 120 printf("(%d, %d)\n",(*it).x-1,(*it).y-1); 121 } 122 return 0; 123 }