编程算法 - 迷宫的最短路径 代码(C++)
发布时间:2020-12-16 07:42:26 所属栏目:百科 来源:网络整理
导读:今天PHP站长网 52php.cn把收集自互联网的代码分享给大家,仅供参考。 /* * main.cpp * * Created on: 2014.7.17 * Author: spike *//*eclipse cdt,gcc 4.8.1*/#include stdio.h#include limits.h#include utility#include
|
以下代码由PHP站长网 52php.cn收集自互联网 现在PHP站长网小编把它分享给大家,仅供参考 /*
* main.cpp
*
* Created on: 2014.7.17
* Author: spike
*/
/*eclipse cdt,gcc 4.8.1*/
#include <stdio.h>
#include <limits.h>
#include <utility>
#include <queue>
using namespace std;
class Program {
static const int MAX_N=20,MAX_M=20;
const int INF = INT_MAX>>2;
typedef pair<int,int> P;
char maze[MAX_N][MAX_M+1] = {
"#S######.#","......#..#",".#.##.##.#",".#........","##.##.####","....#....#",".#######.#","....#.....",".####.###.","....#...G#"
};
int N = 10,M = 10;
int sx=0,sy=1; //起点坐标
int gx=9,gy=8; //重点坐标
int d[MAX_N][MAX_M];
int dx[4] = {1,-1,0},dy[4] = {0,1,-1}; //四个方向移动的坐标
int bfs() {
queue<P> que;
for (int i=0; i<N; ++i)
for (int j=0; j<M; ++j)
d[i][j] = INF;
que.push(P(sx,sy));
d[sx][sy] = 0;
while (que.size()) {
P p = que.front(); que.pop();
if (p.first == gx && p.second == gy) break;
for (int i=0; i<4; i++) {
int nx = p.first + dx[i],ny = p.second + dy[i];
if (0<=nx&&nx<N&&0<=ny&&ny<M&&maze[nx][ny]!='#'&&d[nx][ny]==INF) {
que.push(P(nx,ny));
d[nx][ny]=d[p.first][p.second]+1;
}
}
}
return d[gx][gy];
}
public:
void solve() {
int res = bfs();
printf("result = %dn",res);
}
};
int main(void)
{
Program P;
P.solve();
return 0;
}
以上内容由PHP站长网【52php.cn】收集整理供大家参考研究 如果以上内容对您有帮助,欢迎收藏、点赞、推荐、分享。 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
