[英]Breadth first search not working 100%
正在为邻接矩阵建立bfs,该矩阵以链接列表的数组形式构建。
这是我的bfs方法,接收链接列表和起始位置的数组:
public static int bfs(List<Integer>[] smallWorld, int start){
int distance = 0;
int size = smallWorld.length;
//for each location in smallWorld do a bfs to every other location
int u;
int white = 0, grey = 1, black = 2;
int [] color, d, pie;
Queue <Integer> q = new <Integer> LinkedList();
color = new int [size];
d = new int [size];
pie = new int [size];
for( int x = 0; x < size; x++){
color[x] = white;
d[x] = -1;
pie[x] = -1;
}
color[start] = grey;
d[start] = 0;
pie[start] = -1;
q.addAll(smallWorld[start]); //enqueue the adjacent items
while(!q.isEmpty()){
u = q.remove();
for(int v = 0; v < smallWorld[u].size(); v++){ //for every vertex u is adjacent to
if(color[v] == white){
color[v] = grey;
d[v] = d[u] + 1;
pie[v] = u;
q.addAll(smallWorld[v]);
}
}
color[u] = black;
}
int x = 0;
while(d[x] != -1){
distance = distance + d[x];
x++;
}
真正的smallWorld的长度为500,但出于测试目的,我只是在数组的第一个索引上执行bfs。 (您知道bfs应该返回数组中2个索引之间的最短路径)。 我的矿井已经运行了大约14分钟,我不确定为什么,我的意思是我认为这是因为!isEmpty(),但这只会在其白色迟早必须耗尽的情况下才添加内容。
编辑。 解决了无循环问题,但BFS方法仍然不是100%
任何想法为什么它不起作用? 我的意思是我遵循算法到T,但是该算法通常不指代链表的数组。
解决这个问题的任何想法
问题可能出在while循环中。 您不增加x。
int x = 0;
while(d[x] != -1){
distance = distance + d[x];
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.