I'm trying to convert my recursive algorithm to an iterative one for performance improvement purposes as my program is trying to get all paths from a text file that has maze. I know that DP is quicker than iterative but I would love to see the differences between recursive, iterative and DP when it comes to this problem.
I'm wondering if there's a way to convert my algorithm to iterative without using stack.
Here's what I've done so far with my recursion.
int[][] maze = new int[Integer.valueOf(dimensions[1])]
[Integer.valueOf(dimensions[0])];
int colA = maze[0].length;
int colB = colA;
int rowA = 0;
int rowB = 0;
for (int i = 0; i < maze.length; i++) {
String currLine = lines.get(i+1);
int j = 0;
for (char c : currLine.toCharArray()) {
maze[i][j] = c == '*' ? -1 : 0;
if (c == 'A') {
maze[i][j] = 1;
rowA = i;
colA = j;
} else if (c == 'B') {
maze[i][j] = 2;
rowB = i;
colB = j;
}
j++;
}
}
return getAllPaths(maze, rowA, colA);
}
private static int getAllPaths(int[][] maze, int i, int j) throws IOException {
if(maze[i][j] == -1) {
return 0;
}
if(maze[i][j] == 2) {
return 1;
}
return getAllPaths(maze, i+1, j) + getAllPaths(maze, i, j+1);
}
Any tips or suggestions where should I start from here to convert this into an iterative will be greatly appreciated!