(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)进行编译和运行。