From 53ed90ab4f3b493f1c3abd4aff4fa45f3f8a0909 Mon Sep 17 00:00:00 2001 From: Kirill Petrashin Date: Thu, 23 Apr 2026 14:37:26 +0300 Subject: Make path reversable in map_editor() --- map.c | 6 ++++++ path.c | 24 +++++++++++++----------- 2 files changed, 19 insertions(+), 11 deletions(-) diff --git a/map.c b/map.c index 005936f..85cc073 100644 --- a/map.c +++ b/map.c @@ -660,6 +660,8 @@ void map_editor(Map *map, size_t *width, size_t *height, Position *start, Positi * * [d] - Switch algorithms (A* or Dijsktra's) * + * [r] - Reverse path + * * [s] - Save the map to a plaintext file * * [q] - Exit the map editor @@ -721,6 +723,10 @@ void map_editor(Map *map, size_t *width, size_t *height, Position *start, Positi if (should_pathfind) path = path_func(dirs, *map, NULL, *width, *height, *start, *goal, visited, 0); break; + case 'r': + path_reverse(&path, *width, *height, start, goal); + break; + case 's': curs_set(2); /* Show the cursor */ echo(); /* Echo characters */ diff --git a/path.c b/path.c index 450ea91..f604ec1 100644 --- a/path.c +++ b/path.c @@ -337,14 +337,19 @@ void path_free(Path path, size_t height) { } void path_reverse(Path *path, size_t width, size_t height, Position *start, Position *end) { - Path new_path = path_new(width, height); - if (new_path == NULL) error("Failed to allocate path\n"); - - Position cur = *end; - while (cur.x != start->x || cur.y != start->y) { - Position parent = (*path)[cur.y][cur.x]; - new_path[parent.y][parent.x] = cur; - cur = parent; + if (*path != NULL) { + Path new_path = path_new(width, height); + if (new_path == NULL) error("Failed to allocate path\n"); + + Position cur = *end; + while (cur.x != start->x || cur.y != start->y) { + Position parent = (*path)[cur.y][cur.x]; + new_path[parent.y][parent.x] = cur; + cur = parent; + } + + path_free(*path, height); + *path = new_path; } /* Switch start and end around */ @@ -356,9 +361,6 @@ void path_reverse(Path *path, size_t width, size_t height, Position *start, Posi end->y ^= start->y; start->y ^= end->y; - path_free(*path, height); - *path = new_path; - return; } -- cgit v1.2.3