C語言實現迷宮問題(超級詳細)

C語言實現迷宮問題

利用棧和遞歸的思想很容易實現,代碼在下面,不懂就問。

#include<stdio.h>
#include<stdlib.h>
#define m 6  
#define n 8 
#define STACK_INIT_SIZE 100 
typedef struct
{
	int x,y;
}SElemType;

typedef struct
{
	SElemType stack[STACK_INIT_SIZE];
	int top;
}SqStack;

typedef struct
{
	int x,y;
}Item;

int maze[m+2][n+2]=
{
	  /*0,1,2,3,4,5,6,7,8,9*/
/*0*/  {1,1,1,1,1,1,1,1,1,1},
/*1*/  {1,0,1,1,1,0,1,1,1,1},
/*2*/  {1,1,0,1,0,1,1,1,1,1},
/*3*/  {1,0,1,0,0,0,0,0,1,1},
/*4*/  {1,0,1,1,1,0,1,1,1,1},
/*5*/  {1,1,0,0,1,1,0,0,0,1},
/*6*/  {1,0,1,1,0,0,1,1,0,1},
/*7*/  {1,1,1,1,1,1,1,1,1,1},
};
int t[m+2][n+2]={0};  //與迷宮相同的二維數組,用來表示該條路有沒有走;
Item Move[8]=       //記錄走的方向;
{
	{0,1},{1,1},{1,0},{1,-1},
              {0,-1},{-1,-1},{-1,0},{-1,1}
};

int sum=0;  //記錄有幾條路徑 


//打印路徑 
void Print(int sum,SqStack a)
{
	int i;
	printf("迷宮的第%d條路徑如下:\n",sum);
	for(i=0;i<=a.top;i++)
		printf("(%d,%d)->",a.stack[i].x,a.stack[i].y);
	printf("出口\n\n");
	printf("\n");
}
 
 
//符合規則的壓入棧 
void Push_SqStack(SqStack *s,SElemType x)
{
	if(s->top==STACK_INIT_SIZE-1)
		printf("\n棧滿!");
	else
	{
		s->top++;
		s->stack[s->top]=x;
	}	
}


//檢查棧是否爲空 
int Empty_SqStack(SqStack *s)
{
	if(s->top==-1)
		return 1;
	else 
		return 0;
} 


//刪除棧頂的元素,退後操作 
void Pop_SqStack(SqStack *s)
{
	if(Empty_SqStack(s))
	{
		printf("\n棧空!");
		exit(0);
	}
	else
	{
		s->top--;
	}
}


void path(int x,int y,SqStack elem)
{
	int i,a,b;
	SElemType temp;
	if(x==6&&y==8)
	{
		sum++;
		Print(sum,elem);
	}
	else
	{
		for(i=0;i<8;i++)          //遍歷八個方向
		{
			a=x+Move[i].x;      
			b=y+Move[i].y;      
			if(!maze[a][b]&&!t[a][b])   
			{
				temp.x=a;temp.y=b;
				t[a][b]=maze[a][b]=1;     //用數組t,M記錄這個位置已經走過了 
				Push_SqStack(&elem,temp);  
				path(a,b,elem);        
				t[a][b]=maze[a][b]=0;     //回溯之後需要將這個位置清空,表示這條路沒有走過
				Pop_SqStack(&elem);		  
			}
		}
	}
}

 

int main()
{
	SqStack *s;
	s=(SqStack *)malloc(sizeof(SqStack));
	s->stack[0].x=1;     
	s->stack[0].y=1;
	s->top=0;             
	t[1][1]=maze[1][1]=1; 
	path(1,1,*s);
	return 0;
}

 

Only if we work harder than others can we achieve ourselves

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章