迷宫问题算法非递归版
golang代码片
package main
import "fmt"
type Point struct {
X int
Y int
}
type Choice struct {
Point
DirIndex int // 当前探索到了哪个方向
}
func PrintChoice(choiceWay []Choice) {
for i := 0; i < len(choiceWay); i++ {
fmt.Printf("%d,%d->", choiceWay[i].Point.X+1, choiceWay[i].Point.Y+1)
}
fmt.Println()
}
func main() {
var choiceWay []Choice
tmp := [200]Choice{}
choiceWay = tmp[:0]
var matrix [7][7]bool = [7][7]bool{ // true为可走,false为墙
{true, true, false, true, false, false, false},
{true, true, false, false, false, false, false},
{false, true, true, false, false, false, false},
{true, false, true, true, false, false, false},
{false, false, true, true, false, false, false},
{false, false, false, true, true, true, false},
{false, false, true, true, false, true, true},
}
var wayTags [7][7]bool // 走过的标记
var start Point = Point{X: 0, Y: 0}
var end Point = Point{X: 6, Y: 6}
var dirs [4]Point = [4]Point{Point{X: 0, Y: -1}, Point{X: 0, Y: 1}, Point{X: -1, Y: 0}, Point{X: 1, Y: 0}}
choiceWay = append(choiceWay, Choice{Point: start, DirIndex: 0})
wayTags[start.X][start.Y] = true
for len(choiceWay) > 0 {
choiceLen := len(choiceWay)
choice := &choiceWay[choiceLen-1]
if choice.X == end.X && choice.Y == end.Y {
PrintChoice(choiceWay)
wayTags[choice.X][choice.Y] = false
choiceWay = choiceWay[:choiceLen-1]
continue
}
haveWay := false
for choice.DirIndex < 4 {
targetPoint := Point{
X: dirs[choice.DirIndex].X + choice.X,
Y: dirs[choice.DirIndex].Y + choice.Y,
}
if targetPoint.X >= 0 && targetPoint.X < 7 && targetPoint.Y >= 0 && targetPoint.Y < 7 {
if wayTags[targetPoint.X][targetPoint.Y] == false &&
matrix[targetPoint.X][targetPoint.Y] {
wayTags[targetPoint.X][targetPoint.Y] = true
choiceWay = append(choiceWay, Choice{
Point: targetPoint,
DirIndex: 0,
})
haveWay = true
choice.DirIndex++
break
}
}
choice.DirIndex++
}
if !haveWay {
wayTags[choice.X][choice.Y] = false
choiceWay = choiceWay[:choiceLen-1]
}
}
}
运行结果: