I borrowed a recursive maze path finder algorithm with the same logic as a working program, but can't figure out why it exceeds run time (the logic claims it's quite efficient)
I'm given a maze where @ is at start (0,0) and walls are "X", paths are "+", exit is at row, column marked as "$". You cannot revisit a place you already visited.
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
|
#include <iostream>
#include <vector>
#include <sstream>
using namespace std;
const char WALL = 'X';
const char PATH = '+';
const char TEMPORARY = '0';
const char MOVE = 'M';
// return how many paths found
int find_maze_path(vector<vector<char>> grid, int r, int c) {
cout << "find_maze_path ["<<r<<"]["<<c<<"]"<<endl;
// testing only
/*
cout<<""
for(int row = 0; row < r; row++) {
for(int col = 0; col < c; col++) {
cout << grid[row][col];
}
cout << endl;
}
*/
if (r < 0 || c < 0 || r >= grid.size() || c >= grid[0].size())
{return 0; } // Cell is out of bounds.
else if (grid[r][c] != PATH && grid[r][c]!= '@' && grid[r][c]!='$')
{return 0; } // cannot move to wall or previously moved areas.
else if (r == grid.size() - 1 && c == grid[0].size() - 1) {
grid[r][c]= MOVE;
return 1; // maze exit.
}
else {
// Recursively find path from neighbor
grid[r][c]= MOVE;
int found = (find_maze_path(grid, r - 1, c) + find_maze_path(grid, r + 1, c) +find_maze_path(grid, r, c - 1) + find_maze_path(grid, r, c + 1 ) );
if (found >0){
return found;
}
else{
grid[r][c] = TEMPORARY; // Dead end.
return 0;
}
}
}
int main(){
int x, y;
cin>>x>>y;
vector<vector<char>> maze_grid;
for (int i=0;i<x; i++){
vector<char> x1;
for (int j=0;j<y; j++){
char temp;
cin>>temp;
x1.push_back(temp);
}
maze_grid.push_back(x1);
}
/*
for (int i = 0; i < maze_grid.size(); i++) {
for (int j = 0; j < maze_grid[i].size(); j++)
cout << maze_grid[i][j];
cout <<" "<< endl;
}
*/
int sol = find_maze_path(maze_grid, 0,0);
cout<<sol;
return 0;
}
|
sample input:
16 18
@ + + + + + + + + + + + + + + + + +
+ + + + + + + + + + + + + + + + + +
+ + + + + + + + + + X + + X + + + X
+ + + + + + + + + X X + + + + + + X
+ + X + + + + + + + + X X + + + + +
+ + + + + + + + + + + + + + X + + +
+ + + + + X + + X + + + + + + X + +
+ + + + + + + + + + + + + + + + + +
+ + + + + + X + + + + + + + + X + +
+ + + + + + + + + + + + + + + + + +
+ + + X + + + + + + + X + + + + X +
+ X X + + X + + + + + + + + + + X +
+ + + + + + + + + + + + + + + + + +
+ X + + + + + X + + + + + + + + X +
+ + X + + + + X + + + X + + + X + +
+ X X + + X + + + + + + + + + X + $
how do I improve this algorithm?