In a school project, we got to solve a maze given through program parameter. To achieve this, we need to use Depth First Search algorithm.
I have been able to find the pseudo code of a DFS algorithm, and even recode it using C. The algorithm is able to find the exit, however now I'm looking for a way to get the path from the beginning to the end of the maze.
The beginning of each maze is the upper left corner, and the end is the bottom right corner.
Initial Maze (X = Walls ; * = Free Space):
*****XX****X********XXXX
XX******XX***XXXXX***XXX
XX***XXXX**XXXXX****XXXX
XX***XXXXXXXXXXXXXX****X
*****XXXXXX****XX***XXXX
XX*************XXXX*****
Solved Maze (o = Path from begining to end):
oooooXXooooXooooooooXXXX
XX**ooooXXoooXXXXX*o*XXX
XX***XXXX**XXXXX***oXXXX
XX***XXXXXXXXXXXXXXo***X
*****XXXXXX****XX**oXXXX
XX*************XXXXooooo
Here is the code I have been able to produce so far:
#include "../include/depth.h"
static t_bool stack_push(t_list **stack, int x, int y)
{
t_cell *cell;
if (!(cell = malloc(sizeof(t_cell))))
return (FALSE);
cell->coord.x = x;
cell->coord.y = y;
if (!my_list_push(stack, cell))
{
free(cell);
return (FALSE);
}
return (TRUE);
}
static t_bool is_colored(const t_list *colored, int x, int y)
{
while (colored != NULL)
{
if (((t_cell *) colored->elm)->coord.x == x &&
((t_cell *) colored->elm)->coord.y == y)
return (TRUE);
colored = colored->next;
}
return (FALSE);
}
static t_bool push_edges(t_map *map, t_stack *stack, int x, int y)
{
if (x - 1 >= 0 && !is_colored(stack->colored, x - 1, y))
stack_push(&stack->stack, x - 1, y);
if (x + 1 < map->sz.x && !is_colored(stack->colored, x + 1, y))
stack_push(&stack->stack, x + 1, y);
if (y - 1 >= 0 && !is_colored(stack->colored, x, y - 1))
stack_push(&stack->stack, x, y - 1);
if (y + 1 < map->sz.y && !is_colored(stack->colored, x, y +1))
stack_push(&stack->stack, x, y + 1);
return (TRUE);
}
static t_bool exit_properly(t_stack *stack, void *curr)
{
my_list_destroy(&stack->stack, LIST_FREE_PTR, NULL);
my_list_destroy(&stack->colored, LIST_FREE_PTR, NULL);
free(curr);
return (TRUE);
}
t_bool depth(t_map *map)
{
t_stack stack;
t_cell *curr;
stack.colored = stack.stack = NULL;
stack_push(&stack.stack, MAP_START_X, MAP_START_Y);
while (stack.stack != NULL)
{
curr = stack.stack->elm;
my_list_pop(&stack.stack, &stack.stack);
if (curr->coord.x == map->sz.x - 1 &&
curr->coord.y == map->sz.y - 1)
return (exit_properly(&stack, curr));
if (!is_colored(stack.colored, curr->coord.x, curr->coord.y))
{
stack_push(&stack.colored, curr->coord.x, curr->coord.y);
push_edges(map, &stack, curr->coord.x, curr->coord.y);
}
free(curr);
}
return (TRUE);
}
The initial algorithm:
1 procedure DFS-iterative(G,v):
2 let S be a stack
3 S.push(v)
4 while S is not empty
5 v = S.pop()
6 if v is not labeled as discovered:
7 label v as discovered
8 for all edges from v to w in G.adjacentEdges(v) do
9 S.push(w)
Thanks.
Note: t_list types holds a generic linked list.