定义一个二维数组:
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)
这是一道典型的广搜题,思路就不说了,路径保存值得学习,我采用指针递归的方式输出路径
void output(node* s)
{
if(s==NULL) return;
output(s->last);
printf("(%d, %d)\n",s->x,s->y);
}
我个人认为这种递归的方式用起来比较爽,但是自己不擅长 啊哈哈哈哈~~~
#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<queue>
using namespace std;
struct node{
int x,y;
int step;
node* last;
};
int next[4][2]={{0,1},{1,0},{0,-1},{-1,0}};
int map[10][10];
int book[10][10]={0};
node* bfs()
{
node* e;
e=(node*)malloc(sizeof(node));
queue<node*> q;
e->x=0;
e->y=0;
e->step=0;
e->last=NULL;
q.push(e);
while(!q.empty())
{
e=q.front();
q.pop();
if(e->x==4&&e->y==4)
return e;
for(int i=0;i<4;i++)
{
int tx=e->x+next[i][0];
int ty=e->y+next[i][1];
if(tx<0||tx>4||ty<0||ty>4||map[tx][ty]||book[tx][ty]) continue;
book[tx][ty]=1;
node* p;
p=(node*)malloc(sizeof(node));
p->x=tx;
p->y=ty;
p->step=e->step+1;
p->last=e;
q.push(p);
}
}
return NULL;
}
void output(node* s)
{
if(s==NULL) return;
output(s->last);
printf("(%d, %d)\n",s->x,s->y);
}
int main()
{
for(int i=0;i<5;i++)
for(int j=0;j<5;j++)
cin>>map[i][j];
book[0][0]=1;
output(bfs());
return 0;
}