0代表墙 1代表通路
算法思想:
- 从入口开始, 通路就压栈, 压栈后将该点标记成2
- 递归搜索4个方向
- 无路可走的时候回溯, 回溯的时候将栈顶位置重新标记成1(解决带环问题)
- 找到出口则输出(找不到则没有输出)
附上代码
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)