迷宫问题算法非递归版

本文介绍了一种使用Golang实现的非递归算法来解决迷宫问题。通过代码片段展示了具体的实现过程,并给出了运行结果。
摘要由CSDN通过智能技术生成

迷宫问题算法非递归版

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]
		}
	}
}

运行结果:在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值