您的位置:首页 > 其它

迷宫-最短路径距离-BFS

2017-04-21 17:14 453 查看
已知条件:

迷宫地图:0-不通,1通

二维数组(N*M)

0 0 0 0 0 0 0 0

4000

0 1 1 0 0 1 0 0

0 0 1 1 1 1 0 0

0 1 1 1 0 1 1 1

1 1 1 0 0 0 0 1

起始点:s(2,2)

求解所有可通过的点到起始点的最短距离。

算法:

#include <iostream>
#include <queue>
#include <fstream>
#include <string>

using namespace std;

typedef pair<int,int> Pos;

int N,M;
//下、右、上、左四个方向
int dx[4]={1,0,-1,0};
int dy[4]={0,1,0,-1};

int *src;//迷宫信息数组
int *dist;//各位置到起始点的最短路径距离
int sx,sy;//起始点位置

//从文件中读取迷宫地图数据
void readData()
{
fstream in;
char c;
in.open("maze.txt");
int k = 0;
int n = 0;
while(!in.eof())
{
in>>c;
if(c == '\n' || c == ' ')
{
n++;
}else
{
src[k++] = c - '0';
}
}
in.close();
N = n;
M = k/n;

src = new int[N*M]; //分配迷宫数组
dist = new int [N*M]; //分配距离数组

}
//利用BFS计算路径距离
void bfs(int ex, int ey)//输入终点位置
{
queue<Pos> que;
int d
[M]; //临时距离数组

for(unsigned int i = 0; i < N; i++)
{
for(unsigned int j = 0; j < M; j++)
{
d[i*N + j] = -1;
}
}
que.push(Pos(sx,sy));
d[sx * N + sy] = 0;
while(que.size())
{
Pos p = que.front();
que.pop();
if(p.first == ex && p.second == ey)
break;
for(unsigned int i = 0; i < 4; i++)
{
int x = p.first + dx[i];
int y = p.second + dy[i];
if(0 <= x && x < N && 0 <= y && y < M && src[x * N + y] != 0 && d[x * N + y] == -1)
{
que.push(P(nx,ny));
d[x * N + y] = d[p.first*N + p.second] + 1;

dist[x * N + y] = d[x * N + y]; //更新距离数组

}
}
}
}
int main()
{
readData();
for(int i = 0; i < N; i++)
{
for(int j = 0; j < N; j++)
{
if(src[i * N + j] == 1 && dist[i * N+ j] == -1)//跳过计算过的位置
{
bfs(i,j);
}
}
}

return 0;
}


                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: