[英]DFS Adjacency matrix wrong traversal (when backtracking)
I am trying for hours to print DFS trace (including when you get stuck and you have to backtrack) but my output is always missing a 0 and having double numbers我尝试了几个小时来打印 DFS 跟踪(包括当你卡住并且必须回溯时),但是我的 output 总是缺少一个 0 并且有双数字
My input matrix is like this我的输入矩阵是这样的
0 1 1 0 0 0 0 0
0 0 0 0 0 0 0 0
0 1 0 0 1 0 1 0
1 0 1 0 0 1 0 0
0 0 0 0 0 1 0 0
0 1 0 0 0 0 0 0
0 0 1 0 0 1 0 0
0 0 0 0 0 1 1 0
My output is like this我的output是这样的
0 0 1 0 2 2 4 4 5 2 6 3 7
But it should be like this但它应该是这样的
0 1 0 2 4 5 4 2 6 2 0 3 7
My algoritem is this one我的算法是这个
public void DFSDriver(int[][] adjMatrix)
{
int[] visitMatrix = new int[adjMatrix[0].length];
DftRecursive(adjMatrix, visitMatrix, 0); //Visit all nodes you can
//Visit the ones you cannot because they are separate
for(int i = 0; i < adjMatrix.length; i++) {
if(visitMatrix[i] != 1) {
DftRecursive(adjMatrix, visitMatrix, i); //Visit the ones you cannot because they are separate
}
}
}
public void DftRecursive(int[][] srcMatrix, int[] visitMatrix, int vertex)
{
visitMatrix[vertex] = 1;
System.out.print(vertex + " ");
for (int neighbour = 0; neighbour < srcMatrix[0].length; neighbour++)
{
if (srcMatrix[vertex][neighbour] == 1 && visitMatrix[neighbour] == 0)
{
System.out.print(vertex + " "); //If I don't print this DFS by itself works fine, but I want to print this because I want to backtrack when I get stuck
DftRecursive(srcMatrix, visitMatrix, neighbour);
}
}
}
Hope someone can figure out what I am doing wrong here (the problem is that I also need to print the backtracking, printing only DFS is fine, but backtracking is harder to do)希望有人能弄清楚我在这里做错了什么(问题是我还需要打印回溯,只打印 DFS 很好,但回溯更难做)
exchanging the print
line and the DftRecursive
line.交换print
行和DftRecursive
行。 like this:像这样:
if (srcMatrix[vertex][neighbour] == 1 && visitMatrix[neighbour] == 0)
{
DftRecursive(srcMatrix, visitMatrix, neighbour);
System.out.print(vertex + " ");
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.