Search code examples
javabreadth-first-searchadjacency-matrixdepth

How can I track the depth of each vertex in a breadth first search of an adjacency matrix? (Java)


I am trying to track and print the depth of each node during a breadth first search of an adjacency matrix.

public class steptwo {
static String matrixFileName = "matrix.txt";

static int[][] matrix;
static int dimensions = 0;

public static void main(String[] args) {

    matrix = analyzeFile();
    bft();

}

static void bft(){

    Scanner input = new Scanner(System.in);
    System.out.println("Please enter the source vertex, 0 to " + (matrix.length-1) + ".");

    int source = input.nextInt()+1;


    //Testing for valid vertex 
    while (source > matrix.length) {
        System.out.println("Invalid vertex, please enter another from 0 to " + (matrix.length-1) + ".");
        source = input.nextInt()+1;
    }
    input.close();

    boolean[] visited = new boolean[matrix.length];

    visited[source - 1] = true;
    Queue<Integer> queue = new LinkedList<>();
    queue.add(source);
    int height = 0;
    System.out.println("The breadth first order is: ");

    while(!queue.isEmpty()){
        System.out.print(queue.peek()-1 + " ---> H");
        int x = queue.poll();
        int i;

        for(i = 0 ; i < matrix.length; i++){
            if(matrix[x-1][i] == 1 && visited[i] == false){
                queue.add(i+1);
                visited[i] = true;
                height++;
            }

        }
        System.out.print(height + "\n");
    }
}

I'm looking for an output formatted like this

Please enter the source vertex, 0 to 7.
0
The breadth first order is: 
0 ---> H5
1 ---> H6
2 ---> H6
3 ---> H6
4 ---> H7
5 ---> H7
6 ---> H7
7 ---> H7

I'm sure I'm just missing something stupid, but I'm at a loss. I need to track the depth of each vertex accessed. The adjacency matrix is successfully being read from a .txt file and works fine in my other methods. I can be any size simple, or not.

Any input is appreciated, Thank you.

If any more information is desired, please let me know.


Solution

  • Make array "depth" with N integers where N is the number of nodes and pass it into BFS
    In BFS, say if you dequeued vertex "u", you discover its neighbors and for each newly discovered neighbor "v" of "u", you set depth[v]=depth[u] + 1:

    if(matrix[x-1][i] == 1 && visited[i] == false){
                    queue.add(i+1);
                    visited[i] = true;
                    depth[i] = depth[x]+1;
                }