巨垃圾的 lua BFS 实现

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值