我试图在图表中查找所有Euler路径。为此,我使用基于此的java代码:http://www.sanfoundry.com/java-program-implement-euler-circuit-problem/(此示例仅查找一个euler路径)。
基本上,我在PrintEulerUtil方法(下面)中进行了一些更改,但这给我带来了算法中的一些问题,而我无法找到有效的解决方案。
以下是代码:
public void printEulerTourUtil(int vertex, int[][] adjacencyMatrix, String trail) {
// variable that stores (in every recursive call) the values of the adj matrix
int[][] localAdjacencyMatrix = new int[this.numberOfNodes + 1][this.numberOfNodes + 1];
// verifies if there is some edge unvisited. if not, then the euler path is in variable "trail"
int verificationSum = 0;
// copy values of variable, not only reference
for (int i = 0; i <= numberOfNodes; i++) {
for (int j = 0; j <= numberOfNodes; j++) {
localAdjacencyMatrix[i][j] = adjacencyMatrix[i][j];
verificationSum += localAdjacencyMatrix[i][j];
}
}
Integer destination = 1;
// if verificationSum != 0, then, at least one edge is in the adj matrix
if (verificationSum != 0) {
// test for every destination possible if is valid (isValidNextEdge) and if has connection between the actual vertex and the destination.
for (destination = 1; destination <= numberOfNodes; destination++) {
if (localAdjacencyMatrix[vertex][destination] == 1 && isValidNextEdge(vertex, destination, localAdjacencyMatrix)) {
// remove the edge for the next recursion call (and not loop the program)
removeEdge(vertex, destination, localAdjacencyMatrix);
trail = trail.concat(destination.toString());
// recursive call
printEulerTourUtil(destination, localAdjacencyMatrix, trail);
}
}
} else {
System.out.println("Euler path: " + trail);
}
}
问题是:当递归调用返回并且目标递增时,图形(邻接矩阵)会遭受一些无法找到新的(nexts)Euler路径的变化。通过示例更容易,所以:
正如您所看到的,例如,在三者的第二级中,当destination等于4时,先前的递归调用已经删除了边1-2和1-3。然后,图形与开始的图形不同......这使得在第一个图形之后无法找到欧拉路径(因为图形不正确)。
有什么想法?如果有人想要我的整个代码,请问。任何帮助都将非常有用。非常感谢你,对不起这篇文章的大小。
答案 0 :(得分:1)
您已经确定了问题!
当递归调用返回并且目标递增时,图形(邻接矩阵)会发生一些变化
在递归函数开始时,您正在获取已传递给您的adjacencyMatrix
的副本。但是,当您遍历可能的目标边时,然后损坏此本地副本。正如您所观察到的那样,在从第一个目标边缘递归调用返回之后,您的localAdjacencyMatrix
已经被更改 - 它不再正确将它传递给递归请求第二个目标边缘。
要解决您的问题,您需要更好地跟踪在中传递给您的邻接矩阵,以及您传递的多个不同的邻接矩阵。< / p>
我还没有检查过这个,但我说你需要:
在// test for every destination possible if is valid (isValidNextEdge) and if has connection between the actual vertex and the destination
之后更改测试,以便它适用于adjacencyMatrix
,传递的不变矩阵
复制将值从adjacencyMatrix
复制到localAdjacencyMatrix
的代码复制到// remove the edge for the next recursion call (and not loop the program)
之前。这将确保在删除边缘时,您可以从输入邻接矩阵的 fresh 副本执行此操作