数据结构:栈 多通路以及带环迷宫的统一解法(lua)

0代表墙 1代表通路

算法思想:

  1. 从入口开始, 通路就压栈, 压栈后将该点标记成2
  2. 递归搜索4个方向
  3. 无路可走的时候回溯, 回溯的时候将栈顶位置重新标记成1(解决带环问题)
  4. 找到出口则输出(找不到则没有输出)

附上代码

local stack = {}
function stack:push(item)
	self[#self+1] = item
end
function stack:pop()
	local pos = self[#self]
	table.remove(self, #self)
	return pos
end
function stack:print()
	for i=1, #self do
		print("[",self[i].x, self[i].y, "]")
	end
end
function stack:lenght()
	return #self
end

local entry = {x=6, y=2}
local maze = { --简单迷宫
	{ 0, 0, 0, 0, 0, 0 },
	{ 0, 0, 1, 0, 0, 0 },
	{ 0, 0, 1, 0, 0, 0 },
	{ 0, 0, 1, 1, 1, 1 },
	{ 0, 1, 1, 0, 1, 0 },
	{ 0, 1, 0, 0, 0, 0 }
};
local maze = { --多出口迷宫
	{ 0, 1, 1, 1, 1, 1 },
	{ 0, 1, 0, 0, 0, 0 },
	{ 0, 1, 1, 1, 1, 1 },
	{ 0, 1, 0, 0, 0, 0 },
	{ 0, 1, 1, 1, 1, 1 },
	{ 0, 1, 0, 0, 0, 0 }
};
local maze = { --有环迷宫
	{ 0, 0, 0, 0, 0, 0 },
	{ 0, 1, 1, 1, 0, 0 },
	{ 0, 1, 0, 1, 1, 0 },
	{ 0, 1, 0, 1, 0, 0 },
	{ 0, 1, 1, 1, 1, 1 },
	{ 0, 1, 0, 0, 0, 0 },
};
function check_exit(pos) --检测出口
	if pos.x==1 or pos.y==1 or pos.x==#maze or pos.y==#maze[1] then
		if pos.x~=entry.x or pos.y~=entry.y and maze[pos.x][pos.y]==1 then
			return true
		end
	end
	return false
end

local search_dir = {{-1,0},{0,1},{1,0},{0,-1}}
function search_maze(pos, s)
	if maze[pos.x] == nil or maze[pos.x][pos.y] == nil or maze[pos.x][pos.y]~=1 then
		return
	end
	s:push(pos)
	if check_exit(pos) then
		s:print()
		print("路径长度为:", s:lenght())
	end
	maze[pos.x][pos.y] = 2
	for i=1, 4 do
		search_maze({x=pos.x+search_dir[i][1], y=pos.y+search_dir[i][2]}, s)
	end
	local p = s:pop()
	maze[p.x][p.y] = 1
end

search_maze(entry, stack)

 

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值