【发布时间】:2021-08-09 01:32:41
【问题描述】:
我正在做一个问题,其中打印从 (0,0) 到 (row-1,cols-1) 的唯一路径.. 但是很难理解 arraylist 的行为。请解释这种行为以及正确的方法。
static void distnctpaths(int maze[][], int i, int j, int r, int c, ArrayList < Integer > path) {
if (i == r && j == c) {
path.add(maze[i][j]);
System.out.println(path);
return;
}
if (i == r + 1 || j == c + 1)
return;
path.add(maze[i][j]);
distnctpaths(maze, i, j + 1, r, c, path);
distnctpaths(maze, i + 1, j, r, c, path);
}
public static void main(String[] args) {
int maze[][] = {
{ 1, 2, 3 },
{ 4, 5, 6 },
{ 7, 8, 9 },
};
ArrayList < Integer > path = new ArrayList < > ();
distnctpaths(maze, 0, 0, 2, 2, path);
}
错误的输出
[1, 2, 3, 6, 9]
[1, 2, 3, 6, 9, 5, 6, 9]
[1, 2, 3, 6, 9, 5, 6, 9, 8, 9]
[1, 2, 3, 6, 9, 5, 6, 9, 8, 9, 4, 5, 6, 9]
[1, 2, 3, 6, 9, 5, 6, 9, 8, 9, 4, 5, 6, 9, 8, 9]
[1, 2, 3, 6, 9, 5, 6, 9, 8, 9, 4, 5, 6, 9, 8, 9, 7, 8, 9]
正确输出(供参考)
[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]
【问题讨论】:
标签: java algorithm object recursion arraylist