定义一个二维数组:
int maze[5][5] = {
0, 1, 0, 0, 0,
0, 1, 0, 1, 0,
0, 0, 0, 0, 0,
0, 1, 1, 1, 0,
0, 0, 0, 1, 0,
};
它表示一个迷宫,其中的1表示墙壁,0表示可以走的路,只能横着走或竖着走,不能斜着走,要求编程序找出从左上角到右下角的最短路线。
Input
一个5 × 5的二维数组,表示一个迷宫。数据保证有唯一解。
Output
左上角到右下角的最短路径,格式如样例所示。
Sample Input
0 1 0 0 0
0 1 0 1 0
0 0 0 0 0
0 1 1 1 0
0 0 0 1 0
Sample Output
(0, 0)
(1, 0)
(2, 0)
(2, 1)
(2, 2)
(2, 3)
(2, 4)
(3, 4)
(4, 4)
这个题感觉还是很难的,首先你得记录下来路径,而队列却有事用完即删,所以我们得想办法,保留下来这些数据,我们可以开一个数组,然后再去开一个pre[]数组,保留这个数据的上一个父节点是谁,结构体中id保存当前节点在数组中的下标
#include<stdio.h>
#include<cstring>
#include<queue>
using namespace std;
int mp[6][6];
int vis[6][6];
int move_x[4]={0,0,1,-1};
int move_y[4]={1,-1,0,0};
typedef struct node
{
int x,y,step;
int id;
}Node;
Node a[30];
int pre[30];
int check(int x,int y)
{
if(vis[x][y]||x<1||x>5||y<1||y>5||mp[x][y])
return 1;
return 0;
}
//这个函数的逻辑结构也是蛮重要的,好好看看,下次就不一定能写出来了
void ans(int id)
{
if(pre[id]==-1)
{
printf("(0, 0)\n");
return;
}
ans(pre[id]);
printf("(%d, %d)\n",a[id].x-1,a[id].y-1);
}
void bfs()
{
queue<Node> q;
Node now,next;
now.x=1,now.y=1,now.step=0,now.id=0; //放下递归终止的条件
q.push(now);
a[0].x = now.x,a[0].y=now.y,a[0].id=0;//进行记录
pre[0]=-1;
int cnt=1;
while(q.size())
{
now=q.front();
q.pop();
if(now.x==5&&now.y==5)
{
ans(now.id);
}
for(int i=0;i<4;i++)
{
next.x=now.x+move_x[i];
next.y=now.y+move_y[i];
if(check(next.x,next.y))
continue;
vis[next.x][next.y]=1;
next.step=now.step+1;
next.id=cnt;
q.push(next);
a[cnt].x=next.x,a[cnt].y=next.y;
pre[cnt]=now.id;
// printf("pre:%d\n",pre[cnt]);
cnt++;
}
};
}
int main()
{
memset(vis,0,sizeof(vis));
for(int i=1;i<=5;i++)
for(int j=1;j<=5;j++)
scanf("%d",&mp[i][j]);
bfs();
return 0;
}