[英]Find path in an undirected graph BFS - Java
我正在编写一个程序来处理具有未加权边的无向图,并且由于我是一个学习者,所以遇到了一些问题。
我必须创建一个方法(与主类在同一类中)来接收图形,初始顶点和结束顶点。 然后,我必须查找是否存在从顶点1到顶点2的路径,并将中间顶点存储在队列中以进行打印(它不一定要最短,如果可能的话最好这样做,但实际上并不需要它)。
假设我有:
我想从中得到唯一的一条路
我已经实现了bfs方法,该方法如下所示,并且也用于其他我拥有的方法,但是我不知道如何从所需的该方法开始。 我的bfs方法:
public static Queue<DecoratedInmate> bfs (Graph gr, Vertex<DecoratedInmate> v){
Queue<Vertex<DecoratedInmate>> vertices = new LinkedList<Vertex<DecoratedInmate>>(); //temporal queue
Queue<DecoratedInmate> traversal = new LinkedList<DecoratedInmate>(); //traversal queue
Vertex<DecoratedInmate> u; //vertex taken from queue
Vertex<DecoratedInmate> z; //opposite vertex of u
Edge e; //edge between vertices
Iterator<Edge<DecoratedInmate>> it; //to store incident edges
v.getElement().setVisited(true); //set received vertex to visited
vertices.offer(v); //add origin vertex to queue
while (!vertices.isEmpty()) { //if queue isn't empty
u = vertices.remove(); //take vertex from queue
traversal.offer(u.getElement()); //add element to list
it = gr.incidentEdges(u); //get incident edges of u
while (it.hasNext()) { //check if there are incident edges
e = it.next(); //assign the edge
z = gr.opposite(u, e); //assign opposite vertex of u
if (!z.getElement().getVisited()) { //check if the opposite is not visited
z.getElement().setVisited(true); //set to visited
vertices.offer(z); //add to queue
}
}
}
return traversal;
}
提前致谢
我对您的问题的理解是,您正在尝试查找从一个节点到另一个节点的路径,而不一定是如何访问它们。 所以这是一个实现。 运行bfs时,存储每个顶点父代,即
public static void Bfs(Vertex source) {
vertex = GraphifyGUI.getNode();
reset();
q = new LinkedList<>(); // FIFO
source.wasVisited = true; // marked as visited
q.add(source); // put into queue
source.parent = source; // set parent
conn = new ArrayList<>();
while (!q.isEmpty()) { // source
Vertex current = q.poll(); // remove first
conn.add(current.getId());
Iterator<Vertex> currentList = current.vList().iterator();
while (currentList.hasNext()) {
Vertex next = currentList.next();
if (next.wasVisited == false) {
next.wasVisited = true;
q.add(next);
next.parent = current;
GG.printlnConsole(next.getName() + " has type of " + next.getType());
}
}
}
GG.printlnConsole("Order is " + conn);
}
然后获得最短路径的方法将如下所示
public void shortestPath(int v, int e) {
if (e == v) {
GG.printlnConsole(v + "-->" + v);
return;
}
for (int i = e; i >= 0; i = vertex.get(i).getParent().getId()) {
if (i == v) {
break;
}
if (vertex.get(i).getParent().getId() != -1) {
set.put(vertex.get(i).getParent().getId(), i);
}
}
}
上面的shortestPath的说明
if this source is the same as destination then that is shortest path
for(i = destination; i >= 0; i = parent of i){
if(i == source) we are done;
if(parent of i is a node) add as path;
谢谢Fafore,我已经解决了。 我要做的是将所有相邻节点设置为最终顶点,并将它们存储在堆栈中,而它们之间的区别在于开始顶点不同。 然后我花了一段时间,直到堆栈为空,然后开始检查哪个堆栈与起始顶点相邻,然后检查哪个堆栈彼此相邻(因为堆栈的第一个与结束顶点相邻),然后将相邻的相加到一个队列。 它不一定非要成为最短路径,但谢谢=)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.