迷宮 遞迴演算法

2022-06-05 05:12:08 字數 2383 閱讀 8787

迷宮,遞迴實現:

1/*2

迷宮之遞迴,能夠輸出所有的路線。3*/

4 #include 5 #include 6

using

namespace

std;

7 typedef struct

positionposition,*pposition;

1112

int mazemaplinenumber =0;13

pposition pmazepath;

14int pathlength = 0;15

bool isoutofborder(int x,int

y);16

void go(pposition pos);//

將當前位置放入迷宮路線中

17void try(int **pmap,pposition begin,pposition end);//

開始找路

18bool

showpath();

19int

main()

3132

//動態生成乙個二維陣列,用於地圖

33for (i=0;i)

38 cout<

;39}40 cout<

41//

該for迴圈主要輸出對應點的座標,節省輸入時間。

42for (i=0;i)

46 cout<

;47}48 pmazepath = new position[mazemaplinenumber*mazemaplinenumber];

49 cout<

please input start's x and y:";

50 cin>>begin->x>>begin->y;

51 cout<

please input end's x and y:";

52 cin>>end->x>>end->y;

53go(begin);

54 pmap[begin->x][begin->y] = 0;55

try(pmap,begin,end);

5657

if(pathlength == 0) cout<

there is no way to pass the maze

"<

58return0;

59}6061

6263

bool isoutofborder(int x,int

y) 67

68void

go(pposition pos)

73void try(int **pmap,pposition begin,pposition end) ,,,};

75 pposition next = new

position;

76 next->x = begin->x;

77 next->y = begin->y;

78//

cout<

方便除錯。。下同

79int i=0;80

if(next->x==end->x && next->y==end->y) else96}

97}9899

}100

101bool

showpath()

107 cout<

path

"<

108for(int i=0;i1;i++)

111 cout<

<1].x<

<1].y<

<

112return

true

;113 }

maze.cpp

之前用棧寫了乙個迷宮,但是無法輸出全部路線,現在學到遞迴函式了,發現能夠全部輸出全部的路線

遞迴雖然占用資源,但是用起來卻是很方便。一步一步踏踏實實的向前進行!加油!

順帶乙個漢諾塔的小函式,同樣是遞迴

1/*2

漢諾塔演算法:1:將a上的n-1個盤子借助c移到b上。

32:將a上的第n個盤子移到c上。

43:將b上的n-1盤子借助a移到c上。5*/

6 #include 7

void game(int n,char a,char b,char c);//

將a上的盤子借助b移動到c

8int

main()

1314

void game(int n,char a,char b,char

c) else

22 }

hanoi.coo

上述兩個應該都算入門級遞迴演算法吧。為以後學習樹和圖打下好的基礎吧。。。加油!

演算法 遞迴(迷宮)

有乙個迷宮地圖,有一些可達的位置,也有一些不可達的位置 障礙 牆壁 邊界 從乙個位置到下乙個位置只能通過向上 或者向右 或者向下 或者向左 走一步來實現,從起點出發,如何找到一條到達終點的通路 package indi.com.algorithms.recursion public class mi...

迷宮問題遞迴演算法

include define max1 100 using namespace std int flag max1 max1 標記該位置是否走過 int jihao 記錄迷宮的通路個數 typedef struct map1 迷宮的鄰接矩陣的結構體 typedef struct sign 記錄迷宮經...

迷宮探路IV 遞迴演算法

迷宮探路 recursive recursivemaze.c 2003 10 16 include include include include include define n 22 define m 22 define maxlen m n int bg m n int aa m n stru...