70,037
社区成员
发帖
与我相关
我的任务
分享
#include<stdio.h>
#include<stdlib.h>
#include <time.h>
#define OVERFLOW -1
#define MAX 100
#define N 100
typedef struct
{
int x;
int y;
int d;
}Data;
typedef struct
{
int pos;
Data data[MAX];
}SNode,*Stack;
Stack InitStack()
{
Stack pStack;
pStack=(Stack)malloc(sizeof(SNode));
if(!pStack)
exit(OVERFLOW);
pStack->pos=-1;
return pStack;
}
int IsEmpty(Stack stack)
{
return stack->pos==-1;
}
void Push(Stack pStack,Data x)
{
if(pStack->pos>=MAX-1)
exit(OVERFLOW);
else
{
pStack->pos++;
pStack->data[pStack->pos]=x;
}
}
void Pop(Stack pStack)
{
if(pStack->pos==-1)
exit(OVERFLOW);
else
pStack->pos--;
}
Data GetTop(Stack pStack)
{
return pStack->data[pStack->pos];
}
Data SetStackElem(int x,int y,int d)
{
Data element;
element.x=x;
element.y=y;
element.d=d;
return element;
}
void DisplayPath(Stack pStack)
{
Data element;
printf("The path is:\n");
while(!IsEmpty(pStack)) //多了个;
{
element=GetTop(pStack);
Pop(pStack);
printf("The node is: %d %d\n",element.x,element.y);
}
}
void MazePath(int maze[][N],int direction[][2],int x1,int y1,int x2,int y2)
{
int i,j,k,g,h;
Stack pStack;
Data element;
pStack=InitStack();
maze[x1][y1]=2;
Push(pStack,SetStackElem(x1,y1,0));
while(!IsEmpty(pStack))//以前多了一个;
{
element=GetTop(pStack);
Pop(pStack);
i=element.x;
j=element.y;
k = element.d;
while (k<=3)//用while
{
g=i+direction[k][0];
h=j+direction[k][1];
if(g==x2&&h==y2&&maze[g][h]==0)
{
Push(pStack,SetStackElem(i,j,k));//把路径上最后一个点放入
DisplayPath(pStack);
return;//怎么会有返回值?
}
if(maze[g][h]==0)
{
maze[g][h]=2;
Push(pStack,SetStackElem(i,j,k+1));
i=g;
j=h;
k=0;
}
else
k++;
}
}
printf("The path has not been found\n");
}
void main()
{
int n;
int i;
int j;
int m[N][N];
int direction[][2]={0,1,1,0,0,-1,-1,0};
do{
printf("input the size of the map\n");
scanf("%d",&n);
} while(n+2>N||n<1);
srand(time(NULL));
for(i=0;i<=n+1;i++)
{
for(j=0;j<=n+1;j++)
{
if (i==0||i==n+1||j==0||j==n+1) m[i][j] = 1;
else m[i][j] = rand()%2;
}
}
m[1][1]=m[n][n]=0;
for (i = 0; i <= n+1;puts(""), ++i)
for (j = 0; j <= n+1;printf("%d\t", m[i][j]), ++j)
;
MazePath(m,direction,1,1,n,n);
}
input the size of the map
3
1 1 1 1 1
1 0 1 0 1
1 0 0 0 1
1 0 1 0 1
1 1 1 1 1
The path is:
The node is: 2 3
The node is: 2 2
The node is: 2 1
The node is: 1 1
Press any key to continue
(路径倒着看)