-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathbfs.lua
More file actions
27 lines (25 loc) · 678 Bytes
/
bfs.lua
File metadata and controls
27 lines (25 loc) · 678 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
function bfs(start, nodes, fn)
local frontier = {start}
local visited = {}
local next = {}
local next_visit = function(node)
local next = {}
local iter = function (n) return not visited[n] end
for _, n in ipairs(nodes[node]) do
if iter(n) then table.insert(next, n) end
end
return next
end
while 0 < #frontier do
next = {}
for _, node in ipairs(frontier) do
table.insert(visited, node)
fn(node)
for _, n in ipairs(next_visit(node)) do
table.insert(next, n)
end
end
frontier = next
end
end
return bfs