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

标签 java breadth-first-search adjacency-matrix depth

我试图在邻接矩阵的广度优先搜索期间跟踪并打印每个节点的深度。

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 文件中读取,并且在我的其他方法中运行良好。我可以是任意大小的简单,也可以不是。

欢迎任何意见,谢谢。

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

最佳答案

使用 N 个整数创建数组“深度”,其中 N 是节点数并将其传递到 BFS
在 BFS 中,假设您将顶点“u”出列,您会发现它的邻居,并且对于“u”的每个新发现的邻居“v”,您设置深度[v]=深度[u] + 1 :

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

关于java - 如何在邻接矩阵的广度优先搜索中跟踪每个顶点的深度? ( java ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58245607/

相关文章:

java - Java 中 ArrayList 和 LinkedList 的区别——性能的原因

algorithm - 使用邻接矩阵作为数据结构的 Kruskal 算法的时间效率

算法计算一组保证赢得比赛的球队

java - 需要帮助读取文本文件

performance - MATLAB 识别 3D 图像中的相邻区域

java - jsoup 不抓取所有元素?

java - 在Java中,如何动态确定数组的类型?

java - java 中的 openGL : moving camera with TouchEvent

java - 广度优先搜索(高峰时间) - 链表队列包含同一板的重复项

python - 如何使用 bfs 找到 n 叉树的最大深度?