Solving a Maze using stacks

The code should print a path of 'x's from start([1][1]) to end([8][13]) by checking for an empty spot in the order of east,south,west and north. If there is no empty spots it marks the spot as a dead end (d) and backtracks by popping the stack. I manage to get to print the first dead end but i am having trouble back tracking the path. I tried setting my row and columns to stackC.top() and stackR.top() on line 90 but all that did was print D in every empty spot.

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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
#include "stdafx.h"
#include <stack>
#include <iostream>

using namespace std;

void printMaze(char maze[][16]);

void printMaze(char maze[][16]) {
		printf(" ");
	for (int i = 0; i <10; i++)
		for (int j = 0; j < 16; j++) {
			if (j == 15)
				printf("\n");
			printf("%c", maze[i][j]);
		}
	printf("\n");
};

int main()
{
	char	maze[10][16] = {
		"OOOOOOOOOOOOOOO",		//start is [1][1] , end is [8][13]
		"O O O OOO O  OO",
		"O             O",
		"O O OOOOOOO O O",	
		"O O   O   O   O",	
		"O OOO  OO  OOOO",
		"O    O O      O",
		"OO O O O OOO OO",
		"OO   O   O    O",
		"OOOOOOOOOOOOOOO"	
		
	};



	printMaze(maze); //prints unsolved maze

	stack<int>stackR;
	stack<int>stackC;

	int r = 1;
	int c = 1;

	bool done = false;

	while (!done){

		if (r == 10 - 2 && c == 16 - 2)
			done = true;

		if (maze[r][c + 1] == ' ')	//checks east
		{
			stackR.push(r);				
			stackC.push(c);
			maze[r][c] = 'x';
			c++;
		}
		else if (maze[r + 1][c] == ' ')	//checks south
		{
			stackR.push(r);				
			stackC.push(c);
			maze[r][c] = 'x';
			r++;
		}
		else if (maze[r][c - 1] == ' ') // checks west
		{
			stackR.push(r);				
			stackC.push(c);
			maze[r][c] = 'x';
			c--;
		}
		else if (maze[r - 1][c] == ' ') //checks north
		{
			stackR.push(r);
			stackC.push(c);
			maze[r][c] = 'x';
			r--;
		}
		else {
			if (!stackR.empty()) //if stack is not empty, mark current pos. as d
								//and back track
			{
				maze[r][c] = 'D';
				
				stackC.pop();
				stackR.pop();
				
				}			
			
			else
			{
				done = true; 
				printMaze(maze); //prints maze solution 
			}

		}
	}

	double test;
	scanf("%lf", &test);
	return 0;
}
Last edited on
The following code works if you correct a simple mistake at the beginning, otherwise it enters an endless loop. You should spot it easily, anyway I added hints.
If you want to see it running step by step, you can uncomment the lines like these:
1
2
// std::cout << "east\n";
// printMaze(maze); 

plus the following in printMaze():
 
// std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); 

In that case, it will wait for an enter after having displayed every maze.

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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
// The code should print a path of 'x's from start([1][1]) to end([8][13]) 
// by checking for an empty spot in the order of east,south,west and north. 
// If there is no empty spots it marks the spot as a dead end (d) and 
// backtracks by popping the stack.
#include <iostream>
#include <limits>
#include <stack>


struct Position {
    Position() = default;
    Position(unsigned row_arg, unsigned col_arg);
    unsigned row {1}, col {1};
};

Position::Position(unsigned row_arg, unsigned col_arg)
    : row {row_arg}, col {col_arg}
    {}


void printMaze(char maze[][16]);
void waitForEnter();


int main()
{
    // start is [1][1] , end is [8][13]
    char maze[10][16] = { "OOOOOOOOOOOOOOO",
                          "O O O OOO O  OO",
                          "O             O",
                          "O O OOOOOOO O O",
                          "O O   O   O   O",
                          "O OOO  OO  OOOO",
                          "O    O O      O",
                          "OO O O O OOO OO",
                          "OO   O   O    O",
                          "OOOOOOOOOOOOOOO" };

    printMaze(maze); //prints unsolved maze
    std::stack<Position> pos;
    Position here;
    bool done = false;
    while (!done) {
        // Arithmetic problem: if exit is at [8][13], then 10-2 == 8, but
        // 16-2 == ??  :-) 
        if (here.row == 10 - 2 && here.col == 16 - 2) {
            done = true;    // ok, but...
            break;          // ...let's simplify the process ;-)
        }

        if (maze[here.row][here.col + 1] == ' ') {    // checks east
            pos.push(here);
            maze[here.row][here.col] = 'x';
            here.col++;
            // std::cout << "east\n";
            // printMaze(maze);
            continue;
        }

        if (maze[here.row + 1][here.col] == ' ') {   // checks south
            pos.push(here);
            maze[here.row][here.col] = 'x';
            here.row++;
            // std::cout << "south\n";
            // printMaze(maze);
            continue;
        }

        if (maze[here.row][here.col - 1] == ' ') {   // checks west
            pos.push(here);
            maze[here.row][here.col] = 'x';
            here.col--;
            // std::cout << "west\n";
            // printMaze(maze);
            continue;
        }
        
        if (maze[here.row - 1][here.col] == ' ') {   // checks north
            pos.push(here);
            maze[here.row][here.col] = 'x';
            here.row--;
            // std::cout << "north\n";
            // printMaze(maze);
            continue;
        }
        
        // If we get, here, it means the path was a dead end
        if (!pos.empty()) {
        // if stack is not empty, mark current pos. as d and back track
            maze[here.row][here.col] = 'D';
            here = pos.top();
            pos.pop();
            // std::cout << "no way\n";
            // printMaze(maze);
            continue;
        }
    }
    printMaze(maze); //prints maze solution
    waitForEnter();
    return 0;
}


void printMaze(char maze[][16])
{
    printf(" ");
    for (int i = 0; i <10; i++) {
        for (int j = 0; j < 16; j++) {
            if (j == 15)
            printf("\n");
            printf("%c", maze[i][j]);
        }
    }
    printf("\n");
    // std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}


void waitForEnter()
{
    std::cout << "\nPress ENTER to continue...\n";
    std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}

Last edited on
That was a silly mistake, thank you.
Topic archived. No new replies allowed.