【发布时间】:2014-08-22 08:07:27
【问题描述】:
我正在尝试在图中查找所有欧拉路径。为此,我使用基于此的 java 代码:http://www.sanfoundry.com/java-program-implement-euler-circuit-problem/(此示例仅找到一个欧拉路径)。
基本上,我对 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);
}
}
问题是:当递归调用返回,并且目的地增加时,图(邻接矩阵)会发生一些变化,无法找到新的(下一个)欧拉路径。举个例子就更容易了,所以:
如您所见,例如,在三者的第二层中,当destination 等于4 时,边1-2 和1-3 已经被之前的递归调用移除。然后,图表与开始的不一样......这使得在第一个之后无法找到欧拉路径(因为图表不正确)。
有什么想法吗?如果有人想要我的整个代码,请问。任何帮助都会非常有用。非常感谢,抱歉帖子的大小。
【问题讨论】:
标签: java algorithm recursion graph