[英]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.