#include <stdio.h>
#include <stdlib.h>
struct node
{
int x;
struct node*next;
};
typedef struct node*pnode;
typedef struct node *top,*linkstack;
linkstack setnullstack_link()
{
linkstack top=(linkstack)malloc(sizeof(struct node));
if(top!=NULL)
top->next=NULL;
else
printf("alloc failure");
return top;
}
int isunllstack_link(linkstack top)
{
if(top->next==NULL)
return 1;
else
return 0;
}
void push_link(linkstack top,int x)
{
pnode p;
p=(pnode)malloc(sizeof(struct node));
if(p==NULL)
printf("alloc failure");
else
{
p->x=x;
p->next=top->next;
top->next=p;
}
}
void pop_link(linkstack top)
{
pnode p;
if(top->next==NULL)
printf("it is empty stack");
else
{
p=top->next;
top->next=p->next;
free(p);
}
}
int top_link(linkstack top)
{
if(top->next==NULL)
printf("it is null stack");
else
return top->next->x;
}
typedef struct maze
{
int size;
int **data;
}Maze;
void IntMaze(Maze *maze,int size)
{
int i;
maze->data=(int**)malloc(sizeof(int *)*size);
for(i=0;i<size;i++)
maze->data[i]=(int*)malloc(sizeof(int)*size);
maze->size=size;
}
void readmaze(Maze*maze,int size)
{
int i,j;
for(i=0;i<maze->size;i++)
for(j=0;j<maze->size;j++)
scanf("%d",&maze->data[i][j]);
}
void writemaze(Maze*maze)
{
int i,j;
for(i=0;i<maze->size;i++)
{
for(j=0;j<maze->size;j++)
printf("%d ",maze->data[i][j]);
printf("\n");
}
}
int MazeDFS(int entryx,int entryy,int exitx,int exity,Maze*maze)
{
int direction[8][2]={{0,1},{1,1},{1,0},{1,-1},{0,-1},{-1,-1},{-1,0},{-1,1}};
linkstack linkstackx=NULL;
linkstack linkstacky=NULL;
int posx,posy;
int preposx,preposy;
int **mark;
int i,j;
int mov;
mark=(int**)malloc(sizeof(int *)*maze->size);
for(i=0;i<maze->size;i++)
mark[i]=(int*)malloc(sizeof(int)*maze->size);
for(i=0;i<maze->size;i++)
for(j=0;j<maze->size;j++)
mark[i][j]=0;
linkstackx=setnullstack_link();
linkstacky=setnullstack_link();
push_link(linkstackx,entryx);
push_link(linkstacky,entryy);
while(!isunllstack_link(linkstackx))
{
preposx=top_link(linkstackx);
preposy=top_link(linkstacky);
pop_link(linkstackx);
pop_link(linkstacky);
mov=0;
while(mov<8)
{
posx=preposx+direction[mov][0];
posy=preposy+direction[mov][1];
if(posx==exitx&&posy==exity)
{
push_link(linkstackx,preposx);
push_link(linkstacky,preposy);
printf("%d %d;",exitx,exity);
while(!isunllstack_link(linkstackx))
{
posx=top_link(linkstackx);
posy=top_link(linkstacky);
pop_link(linkstackx);
pop_link(linkstacky);
printf("%d %d;",posx,posy);
}
return 1;
}
if(maze->data[posx][posy]==0&&mark[posx][posy]==0)
{
mark[posx][posy]=1;
push_link(linkstackx,preposx);
push_link(linkstacky,preposy);
preposx=posx;
preposy=posy;
mov=0;
}
else
mov++;
}
}
return 0;
}
int main()
{
Maze maze;
int mazesize;
int entryx,entryy,exitx,exity;
int find=0;
scanf("%d",&mazesize);
IntMaze(&maze,mazesize);
readmaze(&maze,mazesize);
//writemaze(&maze);
scanf("%d%d%d%d",&entryx,&entryy,&exitx,&exity);
find=MazeDFS(entryx,entryy,exitx,exity,&maze);
if(!find)
printf("failure\n");
}
迷宫:深度优先算法
于 2020-11-06 15:57:52 首次发布