C语言迷宫问题定义一个二维数组,c语言写的迷宫问题

该楼层疑似违规已被系统折叠 隐藏此楼查看此楼

下面是程序

#include

#define OVERFLOW -2

#define ERROR 0

#define NULL 0

#define true 1

#define TRUE 1

#define false 0

#define FALSE 0

#define STACK_INIT_SIZE 100

#define STACKINCREMENT 10

#include

#include

/*

初始化迷宫,1表示通道,0表示墙

*/

typedef struct MStackElem

{

int x;

int y;

int val;

}MStackElem;

typedef struct {

MStackElem * base;

MStackElem * top;

int stackSize;

}MStack;

void initStack(MStack *s) {

s->base = (MStackElem *)malloc(STACK_INIT_SIZE * sizeof(MStackElem));

if (!s->base) {

printf("in initStack()...Failed to initalize the MStack ,no enough space! exit now. ");

exit(OVERFLOW);

}

s->top = s->base;

s->stackSize = STACK_INIT_SIZE;

}

void push(MStack *s,MStackElem e) {

if (s->top - s->base >= s->stackSize) {

s->base = (MStackElem *)realloc(s->base, (STACK_INIT_SIZE+STACKINCREMENT) * sizeof(MStackElem));

if (!s->base) {

printf("in push()...Failed to realloc the MStack ,no enough space! exit now. ");

exit(OVERFLOW);

}

s->top = s->base + s->stackSize;

s->stackSize += STACKINCREMENT;

}

*(s->top++) = e;

}

MStackElem getTop(MStack *s) {

if (s->top == s->base) {

printf("in getTop(),empty stack! exit now. ");

exit(ERROR);

}

else {

return *(s->top - 1);

}

}

void pop(MStack *s) {

if (s->top == s->base) {

printf("in pop(),empty stack! exit now. ");

exit(ERROR);

}

else {

--(s->top);

}

}

MStack realPath,path;

int unPass(MStack path,MStackElem cur) {

int flag = 1;

while(path.top != path.base)

{

MStackElem e = *(path.top - 1);

if (e.x == cur.x&& e.y == cur.y)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
二维数组迷宫问题是一个经典的计算机科学问题,通常涉及到搜索算法和路径规划。在C语言中,我们可以使用深度优先搜索(DFS)或广度优先搜索(BFS)来解决这个问题。这里我将简要描述一个基于DFS的解决方案: 1. 定义迷宫结构:创建一个二维数组表示迷宫,其中0代表空地,1代表墙。 2. 初始状态:设置起点(start)和终点(end)为二维数组中的特定位置,并标记起点为已访问(例如设为-1)。 3. 深度优先搜索:从起点开始,检查当前位置的四个相邻格子(上、下、左、右)。如果相邻格子是空地且未被访问过,就继续探索;如果是墙或终点,则回溯。 4. 递归与栈:使用递归来跟踪搜索路径。每当找到一个新的可访问位置,就将其标记为已访问并保存前一位置作为后退路径。 5. 退出条件:当找到终点时,返回从起点到终点的路径。如果没有找到路径,就说明迷宫不可达。 ```c #include <stdio.h> #define ROWS 5 // 迷宫的行数 #define COLS 5 // 迷宫的列数 // 二维数组表示迷宫 int maze[ROWS][COLS]; // 遍历相邻位置 void explore(int x, int y) { // ... (根据具体规则进行检查和递归) } // 主函数 int main() { int start_row, start_col, end_row, end_col; // 设置起点和终点 // ... (初始化迷宫和起点/终点) if (dfs(start_row, start_col, end_row, end_col)) { // 输出路径 printf("Path found: "); // ... (遍历回溯路径) } else { printf("No path found.\n"); } return 0; } // 深度优先搜索 bool dfs(int row, int col, int goal_row, int goal_col) { // ... (实现递归) } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值