DFS解迷宫问题(Go实现)
首先设置一个地图,S为起点,E为终点,#为墙。
定义个栈一般的路径。
开始递归:
- 将旁边的坐标加入路径(第一次为S所在的位置)
- 判断是否越界、重复、撞墙,若是则返回false到上次递归
- 判断是否到达终点,若是则返回true到上次递归
- 若上述判断均否,开始下一次递归,取得返回值
- 若得到的返回值均为false,说明此路不通,删除尾节点。若此时所有节点被删空(栈空),说明无法走到。返回false到上一次递归
若返回为true,说明当前路径为答案
package main
import (
"fmt"
)
type Point struct {
X, Y int
Towards string
}
func ShowMassage() {
}
// 找到起点和终点
func GetStartPointAndEndPoint(map1 [][]byte) Point {
var startPoint Point
for i, v1 := range map1 {
for j, v2 := range v1 {
if v2 == 'S' {
startPoint.X, startPoint.Y = i, j
}
}
}
return startPoint
}
func Arrive (path *[]Point, map1 [][]byte, dir int, nowPoint Point, test int) bool {
// path为路径 map1为地图 dir为方向(上下左右分别为1423 初始为0)
*path = append(*path, nowPoint) // 当前位置加入路径
if nowPoint.X < 0 || nowPoint.X >= len(map1) || nowPoint.Y < 0 || nowPoint.Y >= len(map1[0]) { // 越界
return false
} else if map1[nowPoint.X][nowPoint.Y] == '#' { // 若撞墙
return false
} else if map1[nowPoint.X][nowPoint.Y] == 'E' { // 如果已到达终点
return true
} else {
for i := 0 ; i < len(*path) - 1; i++ {
if (*path)[i].X == nowPoint.X && (*path)[i].Y == nowPoint.Y { // 重复
return false
}
}
}
// 若既没撞墙也没到终点也没越界也没重复
for dir1 := 1; dir1 < 5; dir1++ {
if dir1 + dir == 5 { // 若前后方向相反
continue
} else {
nextPoint := nowPoint
if dir1 == 1 {
(*path)[len(*path) - 1].Towards = "北"
nextPoint.Y--
} else if dir1 == 2 {
(*path)[len(*path) - 1].Towards = "西"
nextPoint.X--
} else if dir1 == 3 {
(*path)[len(*path) - 1].Towards = "东"
nextPoint.X++
} else if dir1 == 4 {
(*path)[len(*path) - 1].Towards = "南"
nextPoint.Y++
}
if Arrive(path, map1, dir1, nextPoint, test + 1) { // 若到达终点
return true
} else {
*path = append((*path)[:len(*path) - 1]) // 否则删掉新添加nextPoint
}
}
}
// 若所有除了来时以外的方向均不可以
if len(*path) > 0 {
*path = append((*path)[:len(*path)]) // 删掉nowPoint
}
return false
}
func main () {
ShowMassage()
// 路径
var path []Point
// 地图
map1 := [][]byte {{' ','S','#','#','#','#'}, {' ',' ',' ',' ',' ','#'}, {'#','#',' ','#','E','#'}}
// S ####
// # # #
// ## E#
fmt.Println("地图为:")
for i := 0; i < 3; i++ {
fmt.Printf("%c\n", map1[i])
}
fmt.Println()
if Arrive(&path, map1, 0, GetStartPointAndEndPoint(map1), 0) {
fmt.Println(path)
} else {
fmt.Println("无法抵达")
}
}
浙公网安备 33010602011771号