如何解决在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;
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。