简体   繁体   English

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

[英]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我正在寻找格式如下的 output

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.邻接矩阵已成功从 a.txt 文件中读取,并且在我的其他方法中工作正常。 I can be any size simple, or not.我可以是任何大小的简单,也可以不是。

Any input is appreciated, Thank you.任何意见表示赞赏,谢谢。

If any more information is desired, please let me know.如果需要更多信息,请告诉我。

Make array "depth" with N integers where N is the number of nodes and pass it into BFS使用 N 个整数创建数组“深度”,其中 N 是节点数,并将其传递给 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 :在 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;
            }  

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM