Backtracking in a maze

Hey everyone, so essentially I have a maze that I'm trying to solve using stacks. So essentially, the maze is a two dimensional array witht he values

1
2
3
4
5
6
7
8
9
10
11
12
13
  const int maze[12][12]={
{1,1,0,1,1,1,1,1,1,1,1,1},
{1,1,0,1,1,1,1,0,0,0,1,1},
{1,1,0,0,0,1,0,0,1,0,0,0},
{1,0,0,1,0,1,0,1,1,1,1,1},
{1,1,0,0,0,1,0,1,0,0,0,1},
{1,1,0,1,1,1,0,1,0,1,0,1},
{1,0,0,1,1,0,0,1,0,1,0,1},
{1,1,0,1,1,0,1,0,0,1,0,1},
{1,1,0,0,0,0,1,1,0,1,0,1},
{1,0,1,0,1,0,0,0,1,1,0,1},
{1,0,0,0,0,0,1,0,0,0,0,1},
{1,1,1,1,1,1,1,1,1,1,1,1}};


I go about solving it by loading all the directions into a stack, and if the direction is a valid option, changing the coordinates of the player. However, I get stuck in a loop and i do not know how to backtrack. here is my stack

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
  	if (last_move == 'D')
	{
		push ('D');
		push ('U');
		push ('L');
		push ('R');
	}
	else if (last_move == 'U')
	{
		push ('U');
		push ('D');
		push ('L');
		push ('R');
	}

    else if (last_move == 'R')
    {
		push ('R');
		push ('L');
		push ('U');
		push ('D');
	}
    
    else if (last_move == 'L')
    {
		push ('L');
		push ('R');
		push ('U');
		push ('D');
    }
        
    if (last_move != 'D')
	push ('U');
   if (last_move != 'U')
	push ('D');
    if (last_move != 'R')
    	push ('L');
    if (last_move != 'L')
    	push ('R'); 	


Does anyone have an idea of how to backtrack?
In order to backtrack you need to record the history of your moves so that you can "go back" when you hit a wall.
Instead of pushing only the next move on the stack, you should push the current position + the moves not tried from this position.

At any step, the top of the stack contains your state (position + moves).

The algorithm will be something like that:
If your position is invalid (outside the maze or inside a wall), go back to the previous state (ie pop the current state from the stack)
Else, choose a not already tried move.
If all moves have already been tried, go back to the previous state.
Else, mark that move as tried in your state, compute the next position and the associated state, push that state on your stack and do this algorithm again.

Keep doing that as long as the stack is not empty and you've not reached your destination.

If you're interested in this kind of pathfinding problems, you should take a look at the A* algorithm (http://en.wikipedia.org/wiki/A*_search_algorithm).
Topic archived. No new replies allowed.