DFS 邻接矩阵遍历错误(回溯时)

DFS Adjacency matrix wrong traversal (when backtracking)

我尝试了几个小时来打印 DFS 跟踪(包括当你遇到困难并且必须回溯时)但我的输出总是缺少 0 并且有两个数字

我的输入矩阵是这样的

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

我的输出是这样的

0 0 1 0 2 2 4 4 5 2 6 3 7

但应该是这样的

0 1 0 2 4 5 4 2 6 2 0 3 7

我的算法是这个

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); 
            }
        }
    }

希望有人能找出我在这里做错了什么(问题是我还需要打印回溯,只打印DFS就可以了,但是回溯比较难做)

交换 print 行和 DftRecursive 行。 像这样:

if (srcMatrix[vertex][neighbour] == 1 && visitMatrix[neighbour] == 0)
            {
                DftRecursive(srcMatrix, visitMatrix, neighbour); 
                System.out.print(vertex + " ");
            }