首先設定乙個地圖,s為起點,e為終點,#為牆。
定義個棧一般的路徑。
開始遞迴:
將旁邊的座標加入路徑(第一次為s所在的位置)
判斷是否越界、重複、撞牆,若是則返回false到上次遞迴
判斷是否到達終點,若是則返回true到上次遞迴
若上述判斷均否,開始下一次遞迴,取得返回值
若得到的返回值均為false,說明此路不通,刪除尾節點。若此時所有節點被刪空(棧空),說明無法走到。返回false到上一次遞迴
若返回為true,說明當前路徑為答案
package mainimport (
"fmt"
)type point struct
func showmassage()
// 找到起點和終點
func getstartpointandendpoint(map1 byte) point
} }return startpoint
}func arrive (path *point, map1 byte, dir int, nowpoint point, test int) bool else if map1[nowpoint.x][nowpoint.y] == '#' else if map1[nowpoint.x][nowpoint.y] == 'e' else
} }// 若既沒撞牆也沒到終點也沒越界也沒重複
for dir1 := 1; dir1 < 5; dir1++ else else if dir1 == 2 else if dir1 == 3 else if dir1 == 4
if arrive(path, map1, dir1, nextpoint, test + 1) else
} }// 若所有除了來時以外的方向均不可以
if len(*path) > 0
return false
}func main () , , }
// s ####
// # # #
// ## e#
fmt.println("地圖為:")
for i := 0; i < 3; i++
fmt.println()
if arrive(&path, map1, 0, getstartpointandendpoint(map1), 0) else
}
BFS解迷宮問題(Go實現)
改了現有的c 而來的,所以說實話並不滿意。廣度優先搜尋 又稱廣度優先搜尋,簡稱bfs,以下簡稱廣度搜尋 是連通圖的遍歷策略。它之所以被命名是因為它的思想從乙個頂點v0開始,並在其周圍的乙個廣域範圍內徑向傳播。最直觀的經典例子之一就是在迷宮中行走。我們從頭開始,尋找到終點的最短路徑。許多最短路徑演算法...
棧的應用 DFS解迷宮問題
深度優先搜尋dfs求解迷宮問題 找到迷宮的可行路徑的座標,這是乙個搜尋遍歷問題。實現思路 可行的路徑儲存在路徑向量p中,從當前點尋找可行方向,如果可行則next入棧,不行則出棧退回前一點。搜尋可行路徑的 while p.empty 下乙個點 p.back direction if maze next...
迷宮問題dfs
迷宮問題 棧作為深度優先遍歷 dfs 採用的搜尋方法的特點是盡可能先對縱深方向進行搜尋 可以最快的找到解 include define m 8 define n 8 define maxsize 1000 typedef struct box typedef struct sttype 迷宮問題常用...