local QUEUE = require "queue".new()
local map = {
{0, 1, 1, 0, 0},
{0, 0, 1, 1, 0},
{0, 1, 1, 1, 0},
{1, 0, 0, 0, 0},
{0, 0, 1, 1, 0},
}
local visited = {}
local function visit(pos)
if pos and pos.x and pos.y then
print(pos.x, pos.y, map[pos.x][pos.y])
end
end
local function BFS(root)
if not root or not root.x or not root.y then return end
visit(root)
visited[root.x] = visited[root.x] or {}
visited[root.x][root.y] = 1
queue.push(QUEUE, root)
while(not queue.empty(QUEUE)) do
local node = queue.pop(QUEUE)
if node.x and node.y then
if map[node.x - 1] and map[node.x - 1][node.y] and not (visited[node.x - 1] or {})[node.y] then
visit({x = node.x - 1, y = node.y})
visited[node.x - 1] = visited[node.x - 1] or {}
visited[node.x - 1][node.y] = 1
queue.push(QUEUE, {x = node.x - 1, y = node.y})
end
end
if node.x and node.y then
if map[node.x + 1] and map[node.x + 1][node.y] and not (visited[node.x + 1] or {})[node.y] then
visit({x = node.x + 1, y = node.y})
visited[node.x + 1] = visited[node.x + 1] or {}
visited[node.x + 1][node.y] = 1
queue.push(QUEUE, {x = node.x + 1, y = node.y})
end
end
if node.x and node.y then
if map[node.x] and map[node.x][node.y - 1] and not (visited[node.x] or {})[node.y - 1] then
visit({x = node.x, y = node.y - 1})
visited[node.x] = visited[node.x] or {}
visited[node.x][node.y - 1] = 1
queue.push(QUEUE, {x = node.x, y = node.y - 1})
end
end
if node.x and node.y then
if map[node.x] and map[node.x][node.y + 1] and not (visited[node.x] or {})[node.y + 1] then
visit({x = node.x, y = node.y + 1})
visited[node.x] = visited[node.x] or {}
visited[node.x][node.y + 1] = 1
queue.push(QUEUE, {x = node.x, y = node.y + 1})
end
end
end
end
BFS({x = 1, y = 1})
巨垃圾的 lua BFS 实现
最新推荐文章于 2024-08-29 17:47:55 发布