Description
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
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)
水题。。BFS一次,每个点记录其前驱的位置,再倒一下输出即可,代码如下:
#include<iostream>
#include<cstring>
#include<queue>
#include<stack>
using namespace std;
typedef struct node
{
int x,y;
node(int xx=0,int yy=0):x(xx),y(yy){}
}node;
node path[10][10];
bool r[10][10];
int d[4][2]={-1,0,0,1,1,0,0,-1};
int Map[10][10]={0};
bool ok(int x,int y)
{
return x>=1&&x<=5&&y>=1&&y<=5&&Map[x][y]!=1;
}
void BFS()
{
queue<node> q;
memset(r,false,sizeof(r));
node t;
q.push(node(1,1));
r[1][1]=true;
while(!q.empty())
{
t=q.front(),q.pop();
for(int i=0;i<4;++i)
{
int u=t.x+d[i][0],v=t.y+d[i][1];
if(ok(u,v)&&!r[u][v])
{
r[u][v]=true;
path[u][v].x=t.x,path[u][v].y=t.y;
q.push(node(u,v));
if(u==5&&v==5) return;
}
} }
}
void Find()
{
stack<node> s;
int u,v,x,y;
node t;
u=v=5;
while(u!=1||v!=1)
{
s.push(node(u,v));
x=u,y=v;
u=path[x][y].x,v=path[x][y].y;
}
s.push(node(1,1));
while(!s.empty())
{
t=s.top(),s.pop();
cout<<"("<<t.x-1<<", "<<t.y-1<<")"<<endl;
}
}
int main()
{
for(int i=1;i<=5;++i)
{
for(int j=1;j<=5;++j) cin>>Map[i][j];
}
BFS();
Find();
return 0;
}