Your question is not very clear.I assume that possible directions are right one step (eg: (1,1) -> (1,2) ), down one step (eg:(1,1,) -> (2,1)) or both right and down one step(eg: (1,1) -> (2,2)). Otherwise, just as discussed by amit, there could be infinite number of paths.
And the case in your question, there should be three possible paths. Just as nav_jan mentioned, (0,0)->(1,1)->(2,2)->(3,3) is also a possible path.
I designed a recursive method, it is quite easy to understand. Start from (0,0) point and try to move in three directions. If current point is 1, keep moving, otherwise return. Once reaching the (n-1,n-1) point, a valid path is found.
The code is in written Java.
public static List<String> getMatrixPaths(int[][] matrix){
List<String> pathList = new ArrayList<String>();
if(matrix != null && matrix.length > 0){
getMatrixPaths(matrix, 0,0, "", pathList);
}
return pathList;
}
public static void getMatrixPaths(int[][] matrix, int i, int j, String path, List<String> pathList){
int n = matrix.length - 1;
if(i > n || j > n){
return;
}else if( matrix[i][j] == 1){//only 1 is valid
path += String.format(" (%d,%d)", i , j);
if( i ==n && j == n){ // reach (n,n) point
pathList.add(path);
}else {
getMatrixPaths(matrix, i +1, j , path, pathList);
getMatrixPaths(matrix, i , j +1, path, pathList);
getMatrixPaths(matrix, i + 1 , j +1, path, pathList);
}
}
}
Use the matrix in question for test, my result is [ (0,0) (1,0) (1,1) (2,2) (3,3), (0,0) (0,1) (1,1) (2,2) (3,3), (0,0) (1,1) (2,2) (3,3)] .
you may refer to this question: Algorithm for finding all paths in a NxN grid . I think they are quite similar.