C语言栈实现迷宫问题(动态简易版)

(1)需要使用到devc++创建一个c项目

(2)在项目下添加两个文件main.c和map.txt

(3)main.c代码如下:

#include <stdio.h>
#include <malloc.h>
#include <windows.h>

#define M 10//迷宫长
#define N 10//迷宫宽 
#define HZ 100//刷新率(HZ毫秒每次) 
int maze[M][N];//迷宫数组 
int i,j,x=1,y=0;

int dx[]={0,1,0,-1}; //方向数组 
int dy[]={1,0,-1,0};//右,下,左,上

typedef struct path{
	int x,y;
	struct path *next;
}Path;
Path *head=NULL;

void push(int x,int y){
	Path *p=(Path*)malloc(sizeof(Path));
	p->x=x;
	p->y=y;
	p->next=head;
	head=p;
}

void pop(){
	head=head->next;
}


//读入文件 
void in()
{
    FILE* fp;
    fp = fopen ("map.txt", "r");

    for(i=0;i<M;i++)
        for(j=0;j<N;j++)fscanf(fp,"%d",&maze[i][j]);
    maze[1][0]=2;
    fclose(fp);
    fp=NULL;
}
//输出迷宫 
void out(){
	for(i=0;i<M;i++){
        for(j=0;j<N;j++){
        	if(maze[i][j]==1)printf("■");
        	else if(maze[i][j]==2)printf("→");
			else if(maze[i][j]==4)printf("↓");
			else if(maze[i][j]==5)printf("←");
			else if(maze[i][j]==6)printf("↑");
            else printf("□");
        }
        printf("\n");
    }
}

int func(){
	int key=0;
	while(1){
		for(i=0;i<4;i++){
			int tx=x+dx[i];
			int ty=y+dy[i];
			if(maze[tx][ty]==0){
				if(i==0){
					maze[tx][ty]=2;
				} 
				else if(i==1){
					maze[tx][ty]=4;
				}
				else if(i==2){
					maze[tx][ty]=5;
				}
				else if(i==3){
					maze[tx][ty]=6;
				}
				push(tx,ty);
				system("cls");
				out();
				Sleep(HZ);
				x=tx,y=ty,key=1;
				break;
			}
		}
		if(key==0){
			maze[x][y]=3;
			pop();
			system("cls");
			out();
			Sleep(HZ);
			if(head==NULL) return 0;
			x=head->x,y=head->y;
		}
		else key=0;
		
		if(x==8&&y==9)
		{
			return 1;
		}
	}
}

int main()
{
	head=(Path*)malloc(sizeof(Path));
	head->x=1;
	head->y=0;
	head->next=NULL;
    in();
    if(!func()) {
    	printf("找不到路径!");
    	return ;
	}
}

 (4)map.txt代码如下:

1 1 1 1 1 1 1 1 1 1
0 0 0 1 0 0 0 1 0 1
1 0 0 1 0 0 0 1 0 1
1 0 0 0 0 1 1 0 0 1
1 0 1 1 1 0 0 0 0 1
1 0 0 0 1 0 0 0 0 1
1 0 1 0 0 0 1 0 0 1
1 0 0 1 1 1 1 1 1 1
1 0 0 0 0 0 0 0 0 0
1 1 1 1 1 1 1 1 1 1

 (5)进行编译和运行。

​​​​​​​

 

  • 2
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值