【问题标题】:java path from top to the bottom of the grid网格从上到下的java路径
【发布时间】:2013-11-09 21:04:11
【问题描述】:

我经常看到这个问题,但它通常只涉及查找机器人可以走的可能路径的数量。所以,问题是:有 NxN 个网格,一个机器人站在网格的顶部。一次移动只能向右或向下移动。

现在,我想打印出机器人可以走的所有可能路径。给定一个 NxN 矩阵, 从 [0][0] 开始,它必须在 [N-1][N-1] 结束。我尝试的是一个简单的递归解决方案:

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);
}

但我不知道在哪里“重置”当前路径。

假设,给定
1 2 3
4 5 6
7 8 9

矩阵,我的解决方案会给出
[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,4,5,6,9],[1,4,5,8,9],[1,4,7,8,9]?
  • 不,它总是打印 [1,2...] 的东西。正如预期的那样,它确实总共产生了 6 条路径,但每条路径都比前一条路径长 1 条。我不知道在哪里“重置”它。
  • 您可以尝试使用不会更改的对象(创建新列表而不是修改现有列表)的纯功能解决方案 - 然后您就不必“重置”任何东西。
  • "每条路径长 1"?我不明白。如果您的解决方案产生 6 条路径,则向我们展示所有 6 条路径,而不仅仅是 3 条。
  • 我已经编辑了我的问题。

标签: java recursion path-finding


【解决方案1】:

这应该可以解决问题。输出是

[[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);
    }
}

【讨论】:

  • 你完全正确。太傻了,我一开始没看到。
  • 你真的不需要将 allPaths 作为递归的一部分传递,让它位于类级别之外
  • @pmminov 你是对的,但在这种情况下,你需要将此方法作为非静态方法放在一个将 allPaths 作为成员的类中,以便在最终的多线程程序中正确使用。
  • 我认为在最后一次调用getPaths中,路径的重复是不需要的。所以 getPaths(A, i+1, j, new ArrayList(path), allPaths) 可以替换为 getPaths(A, i+1, j, path, allPaths)。我修改了代码。
猜你喜欢
  • 2019-01-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-17
  • 1970-01-01
  • 1970-01-01
  • 2018-11-14
  • 1970-01-01
相关资源
最近更新 更多