在链接列表数组上的广度优先搜索[已编辑/缩短并显示错误]

时间:2013-04-10 02:54:20

标签: java search graph linked-list breadth-first-search

我正在研究如何在一个小世界(无向图)中长距离连接如何缩短任何给定节点之间的路径长度。基本上我有一系列链表。数组中的每个部分都链接到任一侧的第一个和第二个邻居,然后实现一些随机连接(建立邻接列表)。

现在我必须在阵列中的每个点上做一个BFS,看看从阵列中的一个点到另一个点需要多少移动。

所以例如这就是阵列的第9个点看起来像

[1, 2]
[0, 2, 3]
[0, 1, 3, 4]
[1, 2, 4, 5]
[2, 3, 5, 6]
[3, 4, 6, 7]
[4, 5, 7, 8, 114]
[5, 6, 8, 9]
[6, 7, 9, 10]
[7, 8, 10, 11]

因为你可以看到数组中的点0与1和2相邻,因为另一侧没有任何东西。 Spot 6有一个远程连接点114。

这是我尝试bfs和我发现一些错误。首先,您认为它看起来如何?但我在行上得到一个空指针异常

u = q.remove();

一个空指针异常。任何想法为什么?你应该等于现在的是1.但是为什么它不会工作。我做了一些打印输出,看看它是否有效,在addAll之后q = [1,2]所以当我打印输出q.remove = 1时,但由于某种原因现在它停止了我的程序!

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 != null){
        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;
    }


    return distance;
}

谢谢你们!

0 个答案:

没有答案