简体   繁体   中英

Breadth first search not working 100%

working on doing a bfs for an adjacency matrix which is buil as an array of linked lists.

Here is my bfs method, receives the array of linked lists and starting location:

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. (Ya know bfs is supposed to give back the shortest possible path between 2 indexes in the array). 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.

EDITED. FIGURED OUT ENDLESS LOOP PROBLEM BUT BFS METHOD STILL NOT 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.

Any ideas to solve this problem

The problem could be in this while loop. You are not incrementing x.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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