Skip to content

Instantly share code, notes, and snippets.

@Mulperi
Last active March 24, 2023 08:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Mulperi/e7c44baac4656f09146b9c6b6cf954cd to your computer and use it in GitHub Desktop.
Save Mulperi/e7c44baac4656f09146b9c6b6cf954cd to your computer and use it in GitHub Desktop.
Breadth first search simple pathfinding
-- Breadth first search.
function Bfs(startCell, targetCell)
local queue = {}
local path = {}
startCell.visited = true
table.insert(queue, startCell)
while #queue > 0 do
local currentCell = queue[1]
table.remove(queue, 1)
if currentCell.x == targetCell.x and currentCell.y == targetCell.y then
table.insert(path, currentCell)
while currentCell.parent do
currentCell = currentCell.parent
table.insert(path, currentCell)
end
break
end
-- Add neighbors to queue if cells are not blocked.
for i = 0, 3 do
if currentCell.neighbors[i]
and not currentCell.neighbors[i].blocked
and not currentCell.neighbors[i].visited
then
table.insert(queue, currentCell.neighbors[i])
currentCell.neighbors[i].visited = true
currentCell.neighbors[i].parent = currentCell
end
end
end
return path
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment