简体   繁体   English

广度优先搜索无法正常工作100%

[英]Breadth first search not working 100%

working on doing a bfs for an adjacency matrix which is buil as an array of linked lists. 正在为邻接矩阵建立bfs,该矩阵以链接列表的数组形式构建。

Here is my bfs method, receives the array of linked lists and starting location: 这是我的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++;
    }

Really smallWorld is of length 500, but for testing purposes im just doing a bfs on the first index in the array. 真正的smallWorld的长度为500,但出于测试目的,我只是在数组的第一个索引上执行bfs。 (Ya know bfs is supposed to give back the shortest possible path between 2 indexes in the array). (您知道bfs应该返回数组中2个索引之间的最短路径)。 Mine has been running for about 14 min now and im not sure why, i mean i assume its because the !isEmpty() but that only adds stuff to the queue if its white so sooner or later that has to run out. 我的矿井已经运行了大约14分钟,我不确定为什么,我的意思是我认为这是因为!isEmpty(),但这只会在其白色迟早必须耗尽的情况下才添加内容。

EDITED. 编辑。 FIGURED OUT ENDLESS LOOP PROBLEM BUT BFS METHOD STILL NOT 100% 解决了无循环问题,但BFS方法仍然不是100%

any ideas why it isnt working? 任何想法为什么它不起作用? I mean i followed the algorithm to the T, but the algorithm generally isnt referring to an array of linked lists. 我的意思是我遵循算法到T,但是该算法通常不指代链表的数组。

Any ideas to solve this problem 解决这个问题的任何想法

The problem could be in this while loop. 问题可能出在while循环中。 You are not incrementing x. 您不增加x。

int x = 0;
while(d[x] != -1){
    distance = distance + d[x];
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM