深度优先迷宫求解实例(C)

本文通过C语言实现深度优先搜索(DFS)算法,详细解析如何利用栈来解决迷宫问题,附带运行截图展示效果。
摘要由CSDN通过智能技术生成
//maze.h
#define RIGHT 0
#define DOWN  1
#define LEFT  2
#define UP    3
typedef struct Position{  //位置
    int x; //行
    int y; //列
}Position;


//顺时针从右开始寻找临近位置,返回该临近位置
Position NextPos(Position now, int dir){
    Position next;
    int x = now.x;
    int y = now.y;

    switch(dir){
        case RIGHT: next.x = x; next.y = y+1; break; //向右走一格
        case DOWN:  next.x = x+1; next.y = y; break; //向下走一格
        case LEFT:  next.x = x; next.y = y-1; break; //向左走一格
        case UP:    next.x = x-1; next.y = y; break; //向上走一格
    }
    return next;
}
//mazeStack.h
#include <stdlib.h>
#include <stdio.h>
#include "maze.h"
#define STACK_INIT_SIZE 100
#define STACKINCREMENT 10
#define MAXSIZE 1000
typedef int Status;

//存入栈中的元素
typedef struct Ele{
    Position pos; //当前位置
    int step;     //当前步数
    int dir;      //当前方向
}Ele;

typedef struct{
    int Stacksize;
    Ele* top;
    Ele* base;
}Stack;

//创建一个栈,返回该栈。创建失败返回NULL
Stack* InitStack(void){
    Stack* s = (Stack*)malloc(sizeof(Stack));
    s->base = (Ele*)malloc(STACK_INIT_SIZE*sizeof(Ele));
    if(!s->base){
        //内存分配失败
        printf(
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值