【问题标题】:Creating an array of distances from a starting vertex in a graph in java在java中创建从图中起始顶点的距离数组
【发布时间】:2021-04-22 07:17:38
【问题描述】:

我在实现使用 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 被分配给距离数组中的相应索引。每次分配当前节点的所有子节点时,随着距离的增加,当前节点将移动到第一个子节点并重复。

【问题讨论】:

    标签: java data-structures graph tree breadth-first-search


    【解决方案1】:

    而不是使用 dist_int 来保存距离值只是调用

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-10-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-09
      相关资源
      最近更新 更多