Find the Shortest Path with A* Search in Larzscript
Search a 2D grid for the shortest route around obstacles - the real A* algorithm (an open set ordered by f = g + h), not a maze-solver toy.
Built on this stack's own heap package for the open set's priority queue - real composability instead of a second hand-rolled heap; 4-directional by default with a Manhattan heuristic.
larzscript pkg install pathfind
Code
import "pathfind" as pf
let g = pf.grid_new(5, 5)
pf.grid_block(g, 1, 1); pf.grid_block(g, 2, 1); pf.grid_block(g, 3, 1)
let path = pf.astar(g, {"x": 0, "y": 0}, {"x": 4, "y": 4})
print("steps:", len(path))
for p in path { print(p["x"], p["y"]) }Output
steps: 9 0 0 1 0 2 0 3 0 4 0 4 1 4 2 4 3 4 4
Related
larzpathfindA* search over a 2D grid, built on this stack's own heap→FizzBuzz in LarzscriptThe classic interview warm-up: print 1 to N, but Fizz for multiples of 3, Buzz for multiples of 5, FizzBuzz for both.→Reverse a String in LarzscriptFlip a string end to end - one of the smallest real string algorithms, and a good first look at the str package.→Check if a String is a Palindrome in LarzscriptDetect whether a string reads the same forwards and backwards, ignoring case, spaces and punctuation.→