为邻接矩阵做一个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应该回放数组中两个索引之间的最短路径)。我现在已经运行了大约14分钟,我不知道为什么,我的意思是我假设它是因为!isEmpty()但是如果它的白色迟早必须用完就只会在队列中添加东西。
编辑。绘制出无限循环问题但是BFS方法仍然不是100%
为什么它不起作用的任何想法?我的意思是我遵循算法到T,但算法通常不是指链接列表数组。
解决此问题的任何想法
答案 0 :(得分:4)
问题可能出在这个while循环中。你没有递增x。
int x = 0;
while(d[x] != -1){
distance = distance + d[x];
}