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

qnakjoqk  于 2021-07-09  发布在  Java
关注(0)|答案(1)|浏览(250)

我很难实现一个方法来创建一个数组的距离使用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;
    }

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

dy2hfwbg

dy2hfwbg1#

不使用dist_int来保存距离值,只需调用
距离[j]=距离[电流]+1;

相关问题