我正在上学,我的方法需要找到从给定节点开始的每个可能的路径。现在问题是,我的方法只找到longests路径,然后停止创建新路径,我似乎无法弄清楚它为什么这样做(可能在Java中缺乏经验)。
我正在使用方法需要迭代的char[3][3]
数组。基本的想法是解决,但不是所有的路径。
我写的方法:
private void computeAllPaths(Point current, ArrayList<Point> currentFullPath) {
if (currentFullPath.isEmpty()) {
currentFullPath.add(current);
}
for (Point coord : neighbouringCoords.get(current)) {
if (!(currentFullPath.contains(coord))) {
currentFullPath.add(coord);
if (!(paths.contains(currentFullPath))) {
paths.add(currentFullPath);
//start over again with same coord
computeAllPaths(currentFullPath.get(0), new ArrayList<Point>());
} else {
//try to add another coord
computeAllPaths(coord, currentFullPath);
}
}
}
}
方法调用:
computeAllPaths(new Point(0, 0), new ArrayList<Point>());
宣言:
private List<ArrayList<Point>> paths = new LinkedList<ArrayList<Point>>();
3x3阵列的一些输出:
Current paths size: 8 (0.0,0.0)(1.0,0.0)(0.0,1.0)(0.0,2.0)(1.0,2.0)(2.0,2.0)(2.0,1.0)(2.0,0.0)(1.0,1.0) (0.0,0.0)(1.0,0.0)(2.0,0.0)(2.0,1.0)(2.0,2.0)(1.0,2.0)(0.0,2.0)(0.0,1.0)(1.0,1.0) (0.0,0.0)(1.0,0.0)(2.0,0.0)(2.0,1.0)(1.0,1.0)(2.0,2.0)(1.0,2.0)(0.0,2.0)(0.0,1.0) (0.0,0.0)(1.0,0.0)(2.0,0.0)(2.0,1.0)(2.0,2.0)(1.0,2.0)(0.0,2.0)(0.0,1.0)(1.0,1.0) (0.0,0.0)(1.0,0.0)(2.0,0.0)(2.0,1.0)(2.0,2.0)(1.0,2.0)(1.0,1.0)(0.0,2.0)(0.0,1.0) (0.0,0.0)(1.0,0.0)(2.0,0.0)(2.0,1.0)(2.0,2.0)(1.0,2.0)(0.0,2.0)(0.0,1.0)(1.0,1.0) (0.0,0.0)(1.0,0.0)(2.0,0.0)(2.0,1.0)(2.0,2.0)(1.0,2.0)(0.0,2.0)(0.0,1.0)(1.0,1.0) (0.0,0.0)(1.0,0.0)(2.0,0.0)(2.0,1.0)(2.0,2.0)(1.0,2.0)(0.0,2.0)(0.0,1.0)(1.0,1.0)
我尝试了很多类型的列表和集合,但似乎没有人工作,我也不知道为什么,有人可以帮我解决这个问题吗?
董事会的例子:
N | N | A
R | E | T
N | T | 0
允许动作: 假设我们从R(1,0)开始,然后允许移动:
答案 0 :(得分:0)
所以我自己不是Java编码器,但是你做的很少。
使用currentFullPath
你要向paths
添加一个指向它的指针,你应该添加一个指向它的副本,所以猜猜会发生什么。将其添加到paths
后,您将在以后进一步更改它。基本上要调试它,只需打印内部循环的每次传递paths
。此外,您应该为currentFullPath
中的每个coord
创建neighbouringCoords
的副本,如果您不这样做,您最终会将所有邻居添加到同一路径。
记住Java始终将指针传递给对象。
编辑: 我看到还有很多废话飞来飞去。试试这个:
private void computeAllPaths(Point current, ArrayList<Point> currentFullPath) {
if (currentFullPath.isEmpty()) {
currentFullPath.add(current);
}
for (Point coord : neighbouringCoords.get(current)) {
if (!(currentFullPath.contains(coord))) {
ArrayList<Point> newList = new ArrayList<Point>(currentFullPath);
newList.add(coord);
if (!(paths.contains(newList))) {
paths.add(newList);
//start over again with same coord
computeAllPaths(currentFullPath.get(0), new ArrayList<Point>());
} else {
//try to add another coord
computeAllPaths(coord, newList);
}
}
}
}
显示结果。
编辑2:这会快得多。
private void computeAllPaths(Point current, ArrayList<Point> currentFullPath) {
if (currentFullPath.isEmpty()) {
currentFullPath.add(current);
}
for (Point coord : neighbouringCoords.get(current)) {
if (!(currentFullPath.contains(coord))) {
ArrayList<Point> newList = new ArrayList<Point>(currentFullPath);
newList.add(coord);
paths.add(newList);
computeAllPaths(coord, new ArrayList<Point>(newList));
}
}
}