如何在邻接矩阵的广度优先搜索中跟踪每个顶点的深度? (Java)

问题描述 投票:0回答:1

我正在尝试在广度优先搜索邻接矩阵的过程中跟踪和打印每个节点的深度。

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

我正在寻找这样的输出格式

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

我确定我只是想念一些愚蠢的东西,但我很茫然。我需要跟踪访问的每个顶点的深度。从.txt文件成功读取了邻接矩阵,并且在我的其他方法中也可以正常工作。我可以是任何简单的大小。

感谢您的任何投入,谢谢。

如果需要更多信息,请告诉我。

java breadth-first-search adjacency-matrix depth
1个回答
1
投票

使用N个整数组成数组“深度”,其中N是节点数,并将其传递到BFS中在BFS中,假设您将顶点“ u”出队,则发现了它的邻居,并为每个新发现的“ u”的邻居“ v”设置了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;
            }  
© www.soinside.com 2019 - 2024. All rights reserved.