From 048bfd21692ea794d01319276796aca759974d8a Mon Sep 17 00:00:00 2001 From: Camden Dixie O'Brien Date: Mon, 4 Nov 2024 22:30:33 +0000 Subject: [PATCH] Rewrite solve procedure to be iterative instead of recursive --- main.c | 64 ++++++++++++++++++++++++++++++---------------------------- 1 file changed, 33 insertions(+), 31 deletions(-) diff --git a/main.c b/main.c index daebc65..0df5c43 100644 --- a/main.c +++ b/main.c @@ -127,41 +127,42 @@ static void generate(vec2_t p) } while (sp != stack); } -static bool solve(vec2_t start, vec2_t *path, vec2_t **end) +static void solve(vec2_t p, vec2_t *sp, vec2_t **end) { - *path++ = start; + *sp++ = p; + while (1) { + if (GOAL == p.x && GOAL == p.y) { + *sp++ = p; + *end = sp; + return; + } - for (int i = 0; i < 4; ++i) { - const vec2_t next = { - .x = start.x + steps[i].x, - .y = start.y + steps[i].y, - }; - const vec2_t im = { - .x = (start.x + next.x) / 2, - .y = (start.y + next.y) / 2, - }; - const bool x_in_bounds = next.x >= 0 && next.x < GRID_SIZE; - const bool y_in_bounds = next.y >= 0 && next.y < GRID_SIZE; + vec2_t n, im; + bool got_n = false; + for (int i = 0; i < 4; ++i) { + n.x = p.x + steps[i].x; + n.y = p.y + steps[i].y; + if (!in_bounds(n)) + continue; - if (x_in_bounds && y_in_bounds) { - const bool accessible = maze[im.x][im.y].is_path; - const bool unvisited = !maze[next.x][next.y].visited; - if (accessible && unvisited) { - maze[next.x][next.y].visited = true; - maze[im.x][im.y].visited = true; - if (GOAL == next.x && GOAL == next.y) { - *path++ = next; - *end = path; - return true; - } - if (solve(next, path, end)) - return true; + im.x = (p.x + n.x) / 2; + im.y = (p.y + n.y) / 2; + if (maze[im.x][im.y].is_path && !maze[n.x][n.y].visited) { + got_n = true; + break; } } - } - --path; - return false; + if (!got_n) { + p = *(--sp); + continue; + } + + maze[im.x][im.y].visited = maze[n.x][n.y].visited = true; + + *sp++ = p; + p = n; + } } int main(void) @@ -221,11 +222,12 @@ int main(void) const vec2_t solve_start = { 0, 0 }; vec2_t path[MAX_PATH_LENGTH], *path_end; maze[0][0].visited = true; - XSetForeground(dpy, ctx, visited_col); - draw_visited(solve_start); solve(solve_start, path, &path_end); + sleep(1); + // Draw solution path + XSetForeground(dpy, ctx, visited_col); const vec2_t *prev = &solve_start; for (const vec2_t *p = path; p < path_end; ++p) { const vec2_t im = {