Last active
March 24, 2023 08:37
-
-
Save Mulperi/e7c44baac4656f09146b9c6b6cf954cd to your computer and use it in GitHub Desktop.
Breadth first search simple pathfinding
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- 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