迷宫问题
输入保存在in.txt文件中:
迷宫中存在通路和障碍,为了方便迷宫的创建,可用0表示通路,用1表示障碍,这样迷宫就可以用0、1矩阵来描述。
8 8
1 1 8 8
0 0 1 0 0 0 1 0
0 0 1 0 0 0 1 0
0 0 0 0 1 1 0 0
0 1 1 1 0 0 0 0
0 0 0 1 0 0 0 0
0 1 0 0 0 1 0 0
0 1 1 1 0 1 1 0
1 0 0 0 0 0 1 0
输出:
附:
读文件涉及的函数: fopen, fscanf
代码:#include<stdio.h>
#include<stdlib.h>
#define STACK_INIT_SIZE 30000
#define TRUE 1
#define FALSE 0
#define OK 1
#define ERROR 0
#define OVERFLOW -2
typedef int Status;
char maze[20][20];
typedef struct{
int r;
int c;
}PosType;
typedef struct{
PosType seat;
int di;
}SElemType;
typedef struct{
SElemType *base;
SElemType *top;
int stacksize;
}SqStack;
SElemType e;
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 StackEmpty(SqStack S)
{
if(S.base==S.top)
return TRUE;
else return FALSE;
}
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 Pass(PosType pos){
if(maze[pos.r][pos.c] == ' ')
return 1;
else
return 0;
}
void FootPrint(PosType pos){
maze[pos.r][pos.c] = '*';
}
void MarkPrint(PosType pos){
maze[pos.r][pos.c] = '@';
}
PosType NextPos(PosType curpos,int i){
switch(i)
{
case 1:
++curpos.c;
break;
case 2:
++curpos.r;
break;
case 3:
--curpos.c;
break;
case 4:
--curpos.r;
break;
}
return curpos;
}
Status MazePath(SqStack &S,PosType start, PosType end){
PosType curpos;
//SqStack S;
SElemType e;
int curstep;
InitStack(S);
curpos = start;
curstep = 1;
do
{
if(Pass(curpos))
{
FootPrint(curpos);
e.seat = curpos;
e.di = 1;
Push(S,e);
if(curpos.r == end.r && curpos.c == end.c)
{
return TRUE;
}
curpos = NextPos(curpos,e.di);
++curstep;
}
else
{
if(!StackEmpty(S))
{
Pop(S,e);
while(e.di == 4 &&!StackEmpty(S))
{
MarkPrint(e.seat);
//maze[curpos.r][curpos.c]='@';
Pop(S,e);
}
if(e.di < 4)
{
++e.di;
Push(S,e);
curpos = NextPos(e.seat,e.di);
}
}
}
}while(!StackEmpty(S));
return FALSE;
}
int main()
{
int x,y,m=0,n=0;
PosType start,end;
int data;
int b[200];
int c=0;
FILE *fp = fopen("in.txt","r");
if(!fp){
printf("can't open file\n");
return -1;
}
while(!feof(fp)){
fscanf(fp,"%d%d%d%d%d%d",&x,&y,&start.r,&start.c,&end.r,&end.c);
for(int i = 0;i<x+2;i++)
{
for(int j = 0;j<y+2;j++)
{
if(i==0||j==0||i==x+1||j==y+1)
maze[i][j]=1;
else
{
fscanf(fp,"%d",&data);
maze[i][j]=data;
}
}
}
for(int m=0;m<10;m++)
{
for(int n=0;n<10;n++)
{
printf("%d",maze[m][n]);
if(n==9)
printf("\n");
}
}
for(int i=0;i<x+2;i++){
for(int j=0;j<y+2;j++){
if(maze[i][j]==1){
maze[i][j]='#';
}else if(maze[i][j]==0){
maze[i][j]=' ';
}
}
}
printf("\n");
SqStack S;
MazePath(S,start,end);
for(int m=0;m<10;m++)
{
for(int n=0;n<10;n++)
{
printf("%c",maze[m][n]);
if(n==9)
printf("\n");
}
}
fclose(fp);
return 0;
}
}