这是我的 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 + "";
}
}