#include <stdio.h>
#include <malloc.h>
struct Node
{
int x;
int y;
};
struct SqStack
{
Node *base;
Node *top;
int stacksize;//数目
};
int data[100][100];
int path[100];
int k=0;
int InitStack(SqStack &maze)//初始化栈
{
maze.base=(Node *)malloc(1000*sizeof(Node));
maze.top=maze.base;
maze.stacksize=1000;
return 1;
}
int GetStack(SqStack maze,Node &e)//得到栈首
{
if (maze.base==maze.top)
{
return 0;
}
e=*(maze.top-1);
printf("得到:%d %d \n",e.x,e.y);
return 1;
}
int PopStack(SqStack &maze,Node &e)//得到栈首不删除
{
if (maze.base==maze.top)
{
return 0;
}
maze.top--;
e.x=maze.top->x;
e.y=maze.top->y;
printf("删除:%d %d \n",e.x,e.y);
return 1;
}
int PushStack(SqStack &maze,Node e)//入栈
{
if((maze.top-maze.base)>=1000)
{
maze.base=(Node*)realloc(maze.base,(100+1000)*sizeof(Node));
maze.top=maze.base+100;
maze.stacksize+=100;
}
*maze.top++=e;
data[e.x][e.y]=1;
return 1;
}
int CompStack(SqStack maze,Node e)//比较
{
if (maze.base==maze.top)
{
return 0;
}
if(e.x==(maze.top-1)->x&&e.y==(maze.top-1)->y)
return 1;
return 0;
}
int MazePath(SqStack &maze,Node start,Node finish,int num)//迷宫算法
{
Node e,temp;
int flog=1;
if(start.x>=num||start.y>=num||finish.x>=num||finish.y>=num||data[start.x][start.y]==1||data[finish.x][finish.y]==1)//不能越界,不能起始结束节点为墙
{
printf("出口或入口不在迷宫内");
return 0;
}
PushStack(maze,start);
while (1)
{
if(CompStack(maze,finish))//比较退出
return 1;
if (flog==0)//如果四周都没找到则删除
{
PopStack(maze,e);
}
flog=0;
GetStack(maze,e);
if(e.y-1<num&&e.y-1>=0&&data[e.x][e.y-1]==0)//左
{
temp.x=e.x;
temp.y=e.y-1;
PushStack(maze,temp);
flog=1;
}
if(e.y+1<num&&e.y+1>=0&&data[e.x][e.y+1]==0)//右
{
temp.x=e.x;
temp.y=e.y+1;
PushStack(maze,temp);
flog=1;
}
if(e.x-1<num&&e.x-1>=0&&data[e.x-1][e.y]==0)//上
{
temp.x=e.x-1;
temp.y=e.y;
PushStack(maze,temp);
flog=1;
}
if(e.x+1<num&&e.x+1>=0&&data[e.x+1][e.y]==0)//下
{
temp.x=e.x+1;
temp.y=e.y;
PushStack(maze,temp);
flog=1;
}
}
}
void main()
{
int num;//记录迷宫大小
Node start,finish;
SqStack maze;
printf("请输入迷宫大小\n");
scanf("%d",&num);
printf("请输入迷宫 :\n");
for(int i=0;i<num;i++)
for(int j=0;j<num;j++)
{
scanf("%d",&data[i][j]);
}
printf("请输入开始入口和最终出口\n");
scanf("%d %d",&start.x,&start.y);
scanf("%d %d",&finish.x,&finish.y);
if(!InitStack( maze))
printf("栈初始化错误");
if(!MazePath(maze,start,finish,num))
return ;
else
{
printf("找到了");
}
}
重点:
1.一开始Get和Pop没分清楚导致错误。
2.主要是为了复习栈的使用。
3.&maze的使用方法与maze,*maze的区别。
4 .算法的技巧性,和算法重复实现不太好,有待改进。