資料結構 迷宮求解

2021-08-19 05:16:39 字數 3179 閱讀 1232

定義迷宮

#include "seqstack.h"

#define max_row 6 //最大行數

#define max_col 6 //最大列數

typedef struct mazemaze;

void mazeinit(maze* maze),,,

,,,};

size_t i = 0;

for(;imap[i][j] = map[i][j];}}

}void mazeprint(maze* maze)

printf("\n");

}printf("\n");

}

引用標頭檔案

#pragma once

#include #include #define for_maze

#ifdef for_maze

typedef struct pointpoint;

typedef point seqstacktype;

#else

typedef char seqstacktype;

#endif

typedef struct seqstackseqstack;

void seqstackinit(seqstack* s);//棧初始化

void seqstackpush(seqstack* s,seqstacktype value);//壓棧

void seqstackresize(seqstack* s);//更改大小

void seqstackpop(seqstack* s);//出棧

int seqstacktop(seqstack* s,seqstacktype* value);//取棧頂元素

void seqstackdestroy(seqstack* s);//銷毀

遞迴版本

//

// round1 遞迴版本

///是否能落腳,能返回1,不能返回0

int canstay(maze* maze,point pt)

int value = maze->map[pt.row][pt.col];

if(value == 1)

return 0;

}void mark(maze* maze,point cur)

int i***it(maze* maze,point cur,point entry)

if(cur.row == 0 || cur.row == max_row-1 || cur.col == 0 || cur.col == max_col-1)

return 0;

}void _getpath(maze* maze,point cur,point entry)

//2.如果能落腳,標記當前點

mark(maze,cur);

//3.判斷當前點是否為出口點,是則直接return

if(i***it(maze,cur,entry))

//4.判斷當前點的上下左右是否有路可走,遞迴判斷

point up = cur;

up.row -= 1;

_getpath(maze,up,entry);

point right = cur;

right.col += 1;

_getpath(maze,right,entry);

point down = cur;

down.row += 1;

_getpath(maze,down,entry);

point left = cur;

left.col -= 1;

_getpath(maze,left,entry);

}void getpath(maze* maze,point entry)

//使用_getpath輔助完成遞迴

_getpath(maze,entry,entry);

}

非遞迴版本

//

// round2 使用非遞迴版本

/void getpathbyloop(maze* maze,point entry)

seqstacktype cur;

//手動維護乙個棧,儲存走過的路徑

seqstack stack;

seqstackinit(&stack);

//1.先判斷是否能落腳,能落腳,當前點入棧

if(!canstay(maze,entry))

seqstackpush(&stack,entry);

//2.如果能落腳,標記當前點

// mark(maze,entry);

//迴圈取棧頂元素

while(seqstacktop(&stack,&cur))

point up = cur;

up.row -= 1;

if(canstay(maze,up))

point right = cur;

right.col += 1;

if(canstay(maze,right))

point down = cur;

down.row += 1;

if(canstay(maze,down))

point left = cur;

left.col -= 1;

if(canstay(maze,left))

seqstackpop(&stack);

}}

測試**

//

// 以下為測試**

/#if 1

#define test_header printf("\n*************************%s********************===\n",__function__)

void test();

getpath(&maze,entry);

mazeprint(&maze);

}void test2();

getpathbyloop(&maze,entry);

mazeprint(&maze);

}int main()

#endif

資料結構 迷宮求解

include include int mg 10 10 地圖 int m 8 行數 int n 8 列數 typedef struct box 定義方塊型別 typedef struct sttype 定義順序棧型別 bool mgpath int xi,int yi,int xe,int ye ...

迷宮求解(資料結構)

include stdio.h include malloc.h define max 10 define l 10 define c 10 int sum l c typedef struct postype typedef struct selemtype typedef struct stac...

資料結構之迷宮求解問題(一)

我們小時候都玩過迷宮,走迷宮可以說是非常有意思了。而在我們大腦裡是如何對這個遊戲進行思考的呢?其實我們在玩這個遊戲的是,大多是一條路走到黑,如果到達出口那麼就走出來了,如果是死胡同,那麼回到剛才的分叉口,再找一條路再一條路走到黑,以此類推。而我們在實現迷宮求解的時候也是利用這種方法,這種方法又稱作回...