Draw shortest path to exit instead of all visited cells
This commit is contained in:
parent
b89b4b64b2
commit
c2a043a8b1
37
main.c
37
main.c
@ -24,6 +24,7 @@
|
||||
#define PX(x) ((x) << 3)
|
||||
|
||||
#define GOAL (GRID_SIZE - 1)
|
||||
#define MAX_PATH_LENGTH (MAZE_SIZE * MAZE_SIZE)
|
||||
|
||||
typedef enum { LEFT, RIGHT, UP, DOWN } dir_t;
|
||||
|
||||
@ -111,8 +112,10 @@ static void generate(vec2_t start)
|
||||
}
|
||||
}
|
||||
|
||||
static bool solve(vec2_t start)
|
||||
static bool solve(vec2_t start, vec2_t *path, vec2_t **end)
|
||||
{
|
||||
*path++ = start;
|
||||
|
||||
for (int i = 0; i < 4; ++i) {
|
||||
const vec2_t next = {
|
||||
.x = start.x + steps[i].x,
|
||||
@ -130,17 +133,19 @@ static bool solve(vec2_t start)
|
||||
const bool unvisited = !maze[next.x][next.y].visited;
|
||||
if (accessible && unvisited) {
|
||||
maze[next.x][next.y].visited = true;
|
||||
draw_visited(next);
|
||||
maze[im.x][im.y].visited = true;
|
||||
draw_visited(im);
|
||||
|
||||
nanosleep(&solve_pause, NULL);
|
||||
if ((GOAL == next.x && GOAL == next.y) || solve(next))
|
||||
if (GOAL == next.x && GOAL == next.y) {
|
||||
*path++ = next;
|
||||
*end = path;
|
||||
return true;
|
||||
}
|
||||
if (solve(next, path, end))
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
--path;
|
||||
return false;
|
||||
}
|
||||
|
||||
@ -199,15 +204,25 @@ int main(void)
|
||||
|
||||
// Solve
|
||||
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);
|
||||
solve(solve_start, path, &path_end);
|
||||
|
||||
// Draw exit path
|
||||
const int x = PX(MARGIN + GRID_SIZE + 1), y = PX(MARGIN + GRID_SIZE);
|
||||
XFillRectangle(dpy, window, ctx, x, y, PX(1), PX(1));
|
||||
XFlush(dpy);
|
||||
// Draw solution path
|
||||
const vec2_t *prev = &solve_start;
|
||||
for (const vec2_t *p = path; p < path_end; ++p) {
|
||||
const vec2_t im = {
|
||||
.x = (prev->x + p->x) / 2,
|
||||
.y = (prev->y + p->y) / 2,
|
||||
};
|
||||
draw_visited(*p);
|
||||
draw_visited(im);
|
||||
nanosleep(&solve_pause, NULL);
|
||||
prev = p;
|
||||
}
|
||||
draw_visited(exit);
|
||||
|
||||
sleep(1);
|
||||
}
|
||||
|
Loading…
x
Reference in New Issue
Block a user