From fefa856b06087179e08aa46a1b6ffa32bee35c34 Mon Sep 17 00:00:00 2001 From: bal7hazar Date: Mon, 9 Sep 2024 16:59:48 -0400 Subject: [PATCH] =?UTF-8?q?=F0=9F=90=9B=20Manage=20impossible=20case?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- crates/pathfinding/src/helpers/astar.cairo | 48 ++++++++++++++++------ 1 file changed, 36 insertions(+), 12 deletions(-) diff --git a/crates/pathfinding/src/helpers/astar.cairo b/crates/pathfinding/src/helpers/astar.cairo index 654afad..8ad482e 100644 --- a/crates/pathfinding/src/helpers/astar.cairo +++ b/crates/pathfinding/src/helpers/astar.cairo @@ -46,19 +46,8 @@ pub impl Astar of AstarTrait { } }; - // [Compute] Reconstruct the path from the target to the start - let mut path: Array = array![]; - let mut current = heap.at(target.position); - loop { - if current.position == start.position { - break; - } - path.append(current.position); - current = heap.at(current.source); - }; - // [Return] The path from the start to the target - path.span() + Self::path(ref heap, start, target) } #[inline] @@ -127,6 +116,27 @@ pub impl Astar of AstarTrait { }; (dx + dy).into() } + + #[inline] + fn path(ref heap: Heap, start: Node, target: Node) -> Span { + // [Check] The heap contains the target + let mut path: Array = array![]; + match heap.get(target.position) { + Option::None => { path.span() }, + Option::Some(mut current) => { + // [Compute] Reconstruct the path from the target to the start + loop { + if current.position == start.position { + break; + } + path.append(current.position); + current = heap.at(current.source); + }; + // [Return] The path from the start to the target + path.span() + }, + } + } } #[cfg(test)] @@ -149,6 +159,20 @@ mod test { assert_eq!(path, array![8, 7, 6, 3].span()); } + #[test] + fn test_astar_search_impossible() { + // x 1 0 + // 1 0 1 + // 0 1 s + let grid: felt252 = 0x1AB; + let width = 3; + let height = 3; + let from = 0; + let to = 8; + let mut path = Astar::search(grid, width, height, from, to); + assert_eq!(path, array![].span()); + } + #[test] fn test_astar_search_medium() { // ┌─x 0 0