I have seen this question quite often, but it usually deals with finding only the number of the possible paths a robot can take. So, the question is: there is NxN grid, and a robot is standing at the top of the grid. In one move, it can move only to the right or to the bottom.
Now, I would like to print out all the possible paths a robot can take. Given an NxN matrix, starting at [0][0], it has to finish at [N-1][N-1]. What I have tried is a simple recursive solution:
public static void getPaths(int[][]A, int i, int j, ArrayList<Integer> path, ArrayList<ArrayList<Integer>> allPaths) {
int n = A.length;
if (i>=n || j>=n) return;
if (i==n-1 && j==n-1) {
path.add(A[i][j]);
allPaths.add(new ArrayList<Integer>(path));
return;
}
path.add(A[i][j]);
getPaths(A, i, j+1, path, allPaths);
getPaths(A, i+1, j, path, allPaths);
path.remove(path.size()-1);
}
but I don't know where to "reset" the current path.
Let's say, given
1 2 3
4 5 6
7 8 9
matrix, my solution would give
[1, 2, 3, 6, 9]
[1, 2, 3, 5, 6, 9]
[1, 2, 3, 5, 6, 8, 9]
[1, 2, 3, 5, 4, 5, 6, 9]
[1, 2, 3, 5, 4, 5, 6, 8, 9]
[1, 2, 3, 5, 4, 5, 6, 7, 8, 9]