设计一个程序,采用深度优先遍历算法的思路,解决迷宫问题。
(1)建立迷宫对应的图数据结构,并建立其邻接表表示。
(2)采用深度优先遍历的思路设计算法,输出从入口(1,1)点到出口(M,N)的所有迷宫路径。
测试用图:
/*
*Copyright (c) 2014,烟台大学计算机学院
*All rights reserved.
*文件名称:Annpion.cpp
*作者:王耀鹏
*完成日期:2016年1月29日
*版本号:v1.0
*
*问题描述:迷宫问题之图深度优先遍历解法
*输入描述:迷宫
*输出描述:迷宫路径
*/
#include <stdio.h>
#include <malloc.h>
#define MaxSize 100
#define M 4
#define N 4
typedef struct ANode //边的结点结构类型
{
int i,j;
struct ANode *nextarc; //该边的终点位置(i,j)
} ArcNode;
typedef struct
{
ArcNode *firstarc; //指向第一条边
} VNode; //指向下一条边的指针
typedef struct
{
VNode adjlist[M+2][N+2]; //邻接表头节点数组
} ALGraph; //图的邻接表类型
typedef struct
{
int i; //当前方块的行号
int j; //当前方块的列号
} Box;
typedef struct
{
Box data[MaxSize];
int length; //路径长度
} PathType; //定义路径类型
int visited[M+2][N+2]= {0};
int count=0;
void CreateList(ALGraph *&G,int mg[][N+2]) //建立迷宫数组对应的邻接表G
{
int i,j,i1,j1,di;
ArcNode *p;
G=(ALGraph *)malloc(sizeof(ALGraph));
for(i=0; i<M+2; ++i)
for(j=0; j<N+2; ++j)
G->adjlist[i][j].firstarc =NULL;
for(i=1; i<=M; ++i)
for(j=1; j<=N; ++j)
if(mg[i][j]==0)
{
di=0;
while(di<4)
{
switch(di)
{
case 0:
i1=i-1;
j1=j;
break;
case 1:
i1=i;
j1=j+1;
break;
case 2:
i1=i+1;
j1=j;
break;
case 3:
i1=i;
j1=j-1;
break;
}
if(mg[i1][j1]==0)
{
p=(ArcNode *)malloc(sizeof(ArcNode));
p->i=i1;
p->j=j1;
p->nextarc=G->adjlist[i][j].firstarc;
G->adjlist[i][j].firstarc=p;
}
++di;
}
}
}
void DispAdj(ALGraph *G)//输出邻接表G
{
int i,j;
ArcNode *p;
for(i=0; i<M+2; ++i)
for(j=0; j<N+2; ++j)
{
printf(" [%d,%d]: ",i,j);
p=G->adjlist[i][j].firstarc;
while(p!=NULL)
{
printf("(%d,%d)",p->i,p->j);
p=p->nextarc;
}
printf("\n");
}
}
void FindPath(ALGraph *G,int xi,int yi,int xe,int ye,PathType path)
{
ArcNode *p;
visited[xi][yi]=1;
path.data[path.length].i=xi;
path.data[path.length].j=yi;
path.length++;
if (xi==xe && yi==ye)
{
printf(" 迷宫路径%d:",++count);
for(int k=0; k<path.length; ++k)
printf("(%d,%d) ",path.data[k].i,path.data[k].j);
printf("\n");
}
p=G->adjlist[xi][yi].firstarc;
while(p!=NULL)
{
if(visited[p->i][p->j]==0)
FindPath(G,p->i,p->j,xe,ye,path);
p=p->nextarc;
}
visited[xi][yi]=0;
}
int main()
{
ALGraph *G;
int mg[M+2][N+2]= //迷宫数组
{
{1,1,1,1,1,1},
{1,0,0,0,1,1},
{1,0,1,0,0,1},
{1,0,0,0,1,1},
{1,1,0,0,0,1},
{1,1,1,1,1,1}
};
CreateList(G,mg);
printf("迷宫对应的邻接表:\n");
DispAdj(G); //输出邻接表
PathType path;
path.length=0;
printf("所有的迷宫路径:\n");
FindPath(G,1,1,M,N,path);
return 0;
}
运行结果: