Search code examples
javamatrixgraphdepth-first-search

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

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

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)


Solution

  • exchanging the print line and the DftRecursive line. like this:

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