前几天写了一个数据结构的迷宫问题,查了全网发现没有结合文件的代码,就自己写了一个,分享一下,也记录一下。
in.txt文件的内容为 第一行是迷宫的行和列 ,第二行是迷宫的起点和终点,后面几行是迷宫的布局,1表示不通,0表示通
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#define TRUE 1
#define FALSE 0
#define OK 1
#define ERROR 0
#define INFEASIBLE -1
#define OVERFLOW -2
#define STACK_INIT_SIZE 100
#define STACKINCREMENT 10
typedef int Status;
int MazeMap[10][10];
typedef struct
{
int row;
int col;
}PosType;
typedef struct
{
int ord;
PosType seat;
int di;
}SElemType;
typedef struct
{
SElemType *base;
SElemType *top;
int stacksize;
}SqStack;
Status InitStack(SqStack *S)
{
(*S).base = (SElemType *)malloc(STACK_INIT_SIZE * sizeof(SElemType));
if(!(*S).base)
exit(OVERFLOW);
(*S).top = (*S).base;
(*S).stacksize = STACK_INIT_SIZE;
return OK;
}
Status Push(SqStack *S,SElemType e)
{
*(*S).top++ = e;
return OK;
}
Status Pop(SqStack *S,SElemType *e)
{
if((*S).top == (*S).base)
return ERROR;
*e = *(--(*S).top);
return OK;
}
Status StackEmpty(SqStack S)
{
if(S.top==S.base)
return OK;
return ERROR;
}
void PrintMaze( )
{
int i,j;
for(i = 0;i<10;i++){
for(j = 0;j<10;j++){
if(MazeMap[i][j] == 1) printf("#");
else if (MazeMap[i][j] == 0) printf(" ");
else if (MazeMap[i][j] == -1) printf("@");
else printf("*");
}
printf("\n");
}
printf("\n");
}
Status FootPrint(PosType pos,int curstep)
{
MazeMap[pos.row][pos.col] = curstep;
return OK;
}
Status Pass(PosType pos)
{
if(MazeMap[pos.row][pos.col] == 0)
return TRUE;
return FALSE;
}
PosType NextPos(PosType CurPos,int i)
{
switch(i)
{
case 1:
++CurPos.col; //东
break;
case 2:
++CurPos.row; //南
break;
case 3:
--CurPos.col; //西
break;
case 4:
--CurPos.row; //北
break;
}
return CurPos;
}
void MakePrint(PosType pos)
{
MazeMap[pos.row][pos.col] = -1;
}
Status MazePath(PosType start,PosType end)
{
SqStack S;
PosType curpos;
SElemType e;
int curstep;
InitStack(&S);
curpos = start;
curstep = 2;
do{
if(Pass(curpos)){
FootPrint(curpos,curstep);
e.ord = curstep;
e.seat = curpos;
e.di = 1;
Push(&S,e);
if(curpos.row == end.row && curpos.col == end.col){
return TRUE;
}
curpos = NextPos(curpos,1);
curstep++;
}
else{
if(!StackEmpty(S)){
Pop(&S,&e);
while(e.di == 4 && !StackEmpty(S)){
MakePrint(e.seat);
Pop(&S,&e);
curstep--;
}
if(e.di < 4){
e.di++;
Push(&S,e);
curpos = NextPos(e.seat,e.di);
}
}
}
}while(!StackEmpty(S));
printf("对不起,找不到出口\n");
return FALSE;
}
int main()
{
int a;
int b;
FILE *fp;
fp = fopen("in.txt","r");
fscanf(fp,"%d%d",&a,&b);
PosType Start,End;
fscanf(fp,"%d%d%d%d",&Start.row,&Start.col,&End.row,&End.col);
for(int i=1;i<=a;i++){
for(int j=1;j<=b;j++){
fscanf(fp,"%d",&MazeMap[i][j]);
}
}
for(int i=0;i<10;i++) MazeMap[i][0] = 1;
for(int i=0;i<10;i++) MazeMap[i][9] = 1;
for(int j=0;j<10;j++) MazeMap[0][j] = 1;
for(int j=0;j<10;j++) MazeMap[9][j] = 1;
PrintMaze();
MazePath(Start,End);
PrintMaze();
return 0;
}
|