java path from top to the bottom of the grid

两盒软妹~` 提交于 2019-12-06 09:59:02

问题


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]


回答1:


This should solve the problem. The output is

[[1, 2, 3, 6, 9], [1, 2, 5, 6, 9], [1, 2, 5, 8, 9], [1, 4, 5, 6, 9], [1, 4, 5, 8, 9], [1, 4, 7, 8, 9]]

.

public class Main {

    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;

        path.add(A[i][j]);

        if (i==n-1 && j==n-1) {
            allPaths.add(path);
            return;
        }
        getPaths(A, i, j+1, new ArrayList<>(path), allPaths);
        getPaths(A, i+1, j, path, allPaths);
    }

    public static void main(String[] args) {
        ArrayList<ArrayList<Integer>> allPaths = new ArrayList<>();
        getPaths(new int[][] { {1,2,3},{4,5,6},{7,8,9}}, 0,0, new ArrayList<Integer>(), allPaths );
        System.out.println(allPaths);
    }
}


来源:https://stackoverflow.com/questions/19883097/java-path-from-top-to-the-bottom-of-the-grid

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!