這是我的bfs算法。我想存儲我在場邊中穿過的邊的數量,但我無法確定將變量放置在哪裏以便爲每個邊添加一個邊。我不斷得到答案太長,所以我認爲這比簡單地增加邊緣更困難。計算廣度優先搜索中遍歷的邊數?
應該指出,這應該只計算沿着真實路徑的邊緣,而不是額外的邊緣。
public int distance(Vertex x, Vertex y){
Queue<Vertex> search = new LinkedList<Vertex>();
search.add(x);
x.visited = true;
while(!search.isEmpty()){
Vertex t = search.poll();
if(t == y){
return edges;
}
for(Vertex n: t.neighbours){
if(!n.visited){
n.visited = true;
search.add(n);
}
}
System.out.println(search + " " + t);
}
return edges;
}
任何和所有的幫助表示讚賞。如果您需要更多的類/方法讓我知道
編輯
import java.util.ArrayList;
public class Vertex {
public static char currentID = 'a';
protected ArrayList<Vertex> neighbours;
protected char id;
protected boolean visited = false;
protected Vertex cameFrom = null;
public Vertex(){
neighbours = new ArrayList<Vertex>();
id = currentID;
currentID++;
Graph.all.add(this);
}
public void addNeighbour(Vertex x){
int a;
while(x == this){
a = (int) (Math.random()*(Graph.all.size()));
x = Graph.all.get(a);
}
if(!(neighbours.contains(x))){
neighbours.add(x);
x.addNeighbour(this);
//System.out.println(this + " Linking to " + x);
}
}
public void printNeighbours(){
System.out.println("The neighbours of: " + id + " are: " + neighbours);
}
public String toString(){
return id + "";
}
}
你能解釋你指的是什麼意思嗎?我從來沒有做過這樣的事情,也許是代碼片段?謝謝! – Lucas 2012-04-08 04:08:16
對不起,通過指針我只是指一個字段 – ulmangt 2012-04-08 04:11:31
哦!這可能有用!我會嘗試,如果它得到upvote +接受:D – Lucas 2012-04-08 04:13:29