【C语言】迷宫自动寻路的实现 Dev C++鬼打墙?

代码根据【数据结构】严蔚敏 版第二章的算法改编而成,其中大部分还借鉴了

点击打开链接 http://www.cnblogs.com/kangjianwei101/p/5221816.html;

特别奇怪和耗掉了我大部分时间的竟然是同一段代码在Dev C++编译运行之后无法显示出多个“死胡同/死锁”标志符,自动结束。换成codeblocks打开项目,编译、运行竟然完全正常。小白不懂为什么,实在是妙不可言。


原理就是做一个栈的抽象数据结构,将走过的路存入栈内。在无路可走时弹出一个元素继续探索其他方向,直到栈为空或者迷宫走出为止。

main.c

#include "Maze.h"


/* run this program using the console pauser or add your own getch, system("pause") or input loop */

int main(int argc, char *argv[]) {
    MazeType maze[N][N];
    PosType start,end;
//    SElemType_Sq e;
    char again='y';
    int flag=0;

    while (again=='y')
    {
        InitMaze(maze,&start,&end);
        ShowMaze(maze);
        flag = MazePath(maze,start,end);
        if (flag==OK){
            printf("\n  We made it!!!");
        } else {
            printf("\n Mission failed.");
        }
        printf("Wanna try again?(y/n)");
        scanf("%c",&again);
    }
	return 0;
}

maze.h

#ifndef Maze_h
#define Maze_h

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include "Status.h"
#include "SequenceStack.h"

//宏定义
#define N 15 //迷宫的大小
#define X 4 //用于随机取余,X越大生成迷宫的通行概率越大

#define SleepTime 2 //代表休眠时间

//迷宫方块的类型定义
typedef enum
{
	Wall,Obstacle,Way,DeadLock, //路径上的死胡同
	East,South,West,North,
	Start,End,
} MazeNode;

迷宫的通道块坐标 注意:x表示从坐标,y表示横坐标
//typedef struct
//{
//	int x;
//	int y;
//} PosType;
通道块信息
//typedef struct
//{
//	int ord; //通道快序列号
//	PosType seat; //坐标位置
//	int di; //下一个该访问的方向 东4 南5 西6 北7
//}SElemType_Sq;

typedef int MazeType; //迷宫元素类型

//函数表
//穷举法的算法
Status MazePath (MazeType maze[][N],PosType start,PosType end);

//初始化
void InitMaze(MazeType maze[][N], PosType *start,PosType *end);

//在屏幕上画出迷宫
void PaintMaze(MazeType[][N]);

//显示迷宫
void ShowMaze (MazeType[][N]);

//比较是否为为同一通道块
Status EqualPosType (PosType a,PosType b);

//判定此通道快是否未访问
Status Passable(PosType seat,MazeType maze[][N]);

//留下初始足迹
void FootPrint (PosType seat,MazeType maze[][N]);

//更新通道快信息
void SetSElemType (SElemType_Sq *e,int ord,PosType seat,int di);

//当前通道快的后继
PosType NextPos (PosType seat, int di);

// 判断是否越界
Status IsCross(PosType seat);

//标记不可访问
void MarkDeadLock(PosType seat,MazeType maze[][N]);

#endif

maze.c

/*顺序栈操作头文件*/

#ifndef Maze_c
#define Maze_c
#include "Maze.h"

//函数表
//穷举法的算法
Status MazePath (MazeType maze[][N],PosType start,PosType end)
{
    SqStack S; //存入步数的栈模型
    SElemType_Sq node; //栈内迷宫格子的存储单位
    PosType curPos; //现在的坐标
    int curStep; //

    InitStack_Sq(&S);
    curPos = start;
    curStep = 1;
    //求得线路即放入栈中
    do {
        if (Passable(curPos,maz

猜你喜欢

转载自blog.csdn.net/as12cs/article/details/80948049