在java中从图中的起始顶点创建距离数组

问题描述

我在实现一种使用 BFS 从选定的起始顶点创建距离数组的方法时遇到问题,它目前在某些情况下似乎有效,但在较大的图形中失败。这个想法是数组中的每个索引代表图中对应的顶点。

这里是相关代码

    public int[] getdistances(Graph g,int startVertex) {
        boolean[] visited = new boolean[g.getNumberOfVertices()];
        int[] distance = new int[g.getNumberOfVertices()];
        for (int i = 0; i < distance.length; i++)
        {
            distance[i] = -1;
        }
        ArrayList<Integer> q = new ArrayList<Integer>();
        q.add(startVertex);
        int dist_int = 0;
        while (!q.isEmpty())
        {
            int current = q.get(0);
            q.remove(0);
            dist_int++;
            visited[startVertex] = true;
            for (int j = 0; j < g.getEdgeMatrix()[current].length; j++)
            {
                if (startVertex == j)
                    distance[j] = 0;
                if (g.getEdgeMatrix()[current][j] == 1 && !visited[j])
                {
                    q.add(j);
                    distance[j] = dist_int;
                    visited[j] = true;
                }
            }
        }
        return distance;
    }

这个想法是它遍历一个邻接矩阵,确定每个未访问的孩子,每次找到一个孩子时,当前的 dist_int 被分配给距离数组中的相应索引。每次当前节点的所有子节点都被分配后,距离增加,然后当前节点移动到第一个子节点并重复。

解决方法

不要使用 dist_int 来保存距离值,只需调用

距离[j] = 距离[当前] + 1;