编写一个程序求解迷宫问题,迷宫是一个m行n列的0-1矩阵,其中0表示无障碍,1表示有障碍,设入口为(1,1),出口为(m,n),每次移动只能从一个无障碍的单元移到其周围8个方向上任一无障碍的单元,编制程序给出一条通过迷宫的路径。
要求:(1)输入m*n的迷宫矩阵,如:
6 9
0 1 0 0 0 1 1 0 0
1 0 0 0 1 1 0 1 1
0 1 1 0 0 0 0 1 1
1 1 0 1 1 1 1 0 1
1 1 0 1 0 0 1 0 0
0 0 1 1 1 0 1 1 0
(2)输出通过迷宫的路径(路径过程反向显示),如果没有迷宫没有路,则输出:不存在路径。
#include<iostream>
#include <queue>
#include<string.h>
using namespace std;
int m,n,flag;
typedef struct point {
int x,y;
point *previous;
int step;
} point;
point dir[8] = {
{ -1, 1, NULL, 0 },
{ 0, 1, NULL, 0 },
{ 1, 1, NULL, 0 },
{ 1, 0, NULL, 0 },
{ 1, -1, NULL, 0 },
{ 0, -1, NULL, 0 },
{ -1, -1, NULL, 0 },
{ -1, 0, NULL, 0 },
};
int map[20][20];
void Print(point *p)
{
int shortest = p->step;
while (p->previous!= NULL)
{
cout << "(" << p->x << "," << p->y << ")"<<' ';
p=p->previous;
}
cout << "(" << p->x<< "," << p->y << ")" << ' '<<endl;
}
void BFS(point startPoint)
{
queue<point> q;
q.push(startPoint);
point cur;
while (!q.empty())
{
cur = q.front();
q.pop();
map[cur.x][cur.y] = 1;
for (int i = 0; i < 8; i++)
{
point nxt{ cur.x + dir[i].x, cur.y + dir[i].y, NULL, 0 };
if (nxt.x > 0 && nxt.x <= m && nxt.y > 0 && nxt.y <= n && map[nxt.x][nxt.y] == 0)
{
point *tmp = new point;
memcpy(tmp, &cur, sizeof(point));
nxt.previous = tmp;
nxt.step = cur.step + 1;
map[nxt.x][nxt.y] = 1;
if (nxt.x==m&&nxt.y==n)
{
Print(&nxt);
flag=1;
return;
}
q.push(nxt);
}
}
}
}
int main()
{
int i,j;
memset(map, 1, sizeof(map));
flag=0;
cin>>m>>n;
for (i = 1; i <= m; i++)
for (j = 1; j <= n; j++)
cin>>map[i][j];
point startPoint={ 1, 1, NULL, 0 };
BFS(startPoint);
if(!flag)
{cout<<"不存在路径!"<<endl;}
}