定义一个二维数组:
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)
#include<iostream>
#include<cstring>
#include<queue>
#include<stdio.h>
struct node
{
int x,y;
};
struct fa
{
int x,y;
}fa[10][10]; //难点主要是路径还原
int a[10][10],vis[10][10];
using namespace std;
void BFS()
{
int next[4][2]={{1,0},{0,1},{0,-1},{-1,0}};
memset(fa,-1,sizeof(fa));
memset(vis,0,sizeof(vis));
queue<node>que;
node p,q;
que.push((node){0,0});
while(!que.empty())
{
p=que.front();
que.pop();
if(p.x==4&&p.y==4)
return ;
for(int i=0;i<4;i++)
{
q.x=p.x+next[i][0];
q.y=p.y+next[i][1];
if(q.x>=0&&q.x<5&&q.y>=0&&q.y<5&&!vis[q.x][q.y]&&a[q.x][q.y]==0)
{
vis[q.x][q.y]=1;
que.push(q);
fa[q.x][q.y].x=p.x;
fa[q.x][q.y].y=p.y;
}
}
}
}
void DFS(int x,int y) //DFS查找前驱结点
{
if(x==0&&y==0)
return ;
DFS(fa[x][y].x,fa[x][y].y);
cout<<"("<<fa[x][y].x<<", "<<fa[x][y].y<<")"<<endl;
}
int main()
{
for(int i=0;i<5;i++)
{
for(int j=0;j<5;j++)
{
cin>>a[i][j];
}
}
BFS();
DFS(4,4);
cout<<"(4, 4)"<<endl; //由于DFS没有输出最后一个点
return 0;
}