// Migong_Queue.cpp : 定义控制台应用程序的入口点。
#include "stdafx.h"
#include "stdlib.h"
#define MaxSize 100
struct
{
int i,j;
int pre;
}Qu[MaxSize];
int front = -1,rear = -1;
int mgpath(int **,int ,int ,int ,int);
void print(int);
int _tmain(int argc, _TCHAR* argv[])
{
int l,h;
FILE *migong=fopen("C:\\Users\\Administrator\\Documents\\Visual Studio 2010\\Projects\\数据结构实验\\Migong_Queue\\migong.txt","r");
if(migong==NULL)
{
printf("Can't open the file!!!");
exit(0);
}
char ch=fgetc(migong);
l=0;
while(ch!='\n')
{
if(ch!=',')
l++;
ch=fgetc(migong);
}//l为迷宫的长度
rewind(migong);
//接下来是算出迷宫的高度h!~~
h=0;
ch=fgetc(migong);
while(!feof(migong))
{
if(ch=='\n')
h++;
ch=fgetc(migong);
}
if(l<5||h<5)
{
printf("It's too small!");
exit(0);
}
rewind(migong);
int **mg=(int **)malloc(sizeof(int *)*h);
for(int h_=0;h_
mg[h_]=(int *)malloc(sizeof(int)*l);
}
for(int h_=0;h_
for(int l_=0;l_
ch=fgetc(migong);
if(ch!=',')
{mg[h_][l_]=ch-'0';l_++;}
}
ch=fgetc(migong);
}
fclose(migong);
printf("The map is presented as follows:\n");
for(int _x=0;_x
printf("%d ",mg[_x][_y]);
if((_y+1)%l==0)
printf("\n");
}
mgpath(mg,1,1,8,8);
return 0;
}
int mgpath(int **mg,int xi,int yi,int xe,int ye)
{
int i,j,find=0,di;
rear++;
Qu[rear].i=xi;
Qu[rear].j=yi;
Qu[rear].pre=-1;
mg[xi][yi]=-1;
while(front<=rear&&!find)
{
front++;
i=Qu[front].i;j=Qu[front].j;
if(i==xe&&j==ye)
{
find=1;
print(front);
return 1;
}
for(di=0;di<4;di++)
{
switch(di)
{
case 0:i=Qu[front].i-1;j=Qu[front].j;break;
case 1:i=Qu[front].i;j=Qu[front].j+1;break;
case 2:i=Qu[front].i+1;j=Qu[front].j;break;
case 3:i=Qu[front].i;j=Qu[front].j-1;break;
}
if(mg[i][j]==0)
{
rear++;
Qu[rear].i=i;Qu[rear].j=j;
Qu[rear].pre=front;
mg[i][j]=-1;
}
}
}
return 0;
}
void print(int front)
{
int k=front,j,ns=0;
printf("\n");
do
{
j=k;
k=Qu[k].pre;
Qu[j].pre=-1;
}while(k!=0);
printf("迷宫路径如下:\n");
k=0;
while(k
if(Qu[k].pre==-1)
{
ns++;
printf("\t(%d,%d)",Qu[k].i,Qu[k].j);
if(ns%5==0)printf("\n");
}
k++;
}
printf("\n");
}
我是从文件中读取迷宫数组的!
你也可以改为直接输入!
希望对你有帮助!谢谢!
哦