简体   繁体   English

在无向图BFS中查找路径-Java

[英]Find path in an undirected graph BFS - Java

I'm making a program to deal with an undirected graph with unweighted edges and since I'm a learner I'm having some issues. 我正在编写一个程序来处理具有未加权边的无向图,并且由于我是一个学习者,所以遇到了一些问题。

I have to make a method (in the same class as the main) which receives the graph, a initial vertex and an end vertex. 我必须创建一个方法(与主类在同一类中)来接收图形,初始顶点和结束顶点。 Then I have to find if there is a path from vertex1 to the vertex2 and store the intermediate vertices in a queue to then print it (it doesn't have to be the shortest, ofc it's better if that's possible but don't really need it). 然后,我必须查找是否存在从顶点1到顶点2的路径,并将中间顶点存储在队列中以进行打印(它不一定要最短,如果可能的话最好这样做,但实际上并不需要它)。

Let's say I have: 假设我有:

Graph 图形

And I wanna get the only ONE path from 我想从中得到唯一的一条路

I have implemeted a bfs method, which is the following and is used for other methods I have also, but I don't know how to start with this method I need. 我已经实现了bfs方法,该方法如下所示,并且也用于其他我拥有的方法,但是我不知道如何从所需的该方法开始。 My bfs method: 我的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;
}

Thanks in advance 提前致谢

My understanding of your problem is that you are trying to find a path from one node to another and not necessarily how they are visited. 我对您的问题的理解是,您正在尝试查找从一个节点到另一个节点的路径,而不一定是如何访问它们。 So here is an implementation. 所以这是一个实现。 When running bfs, store each vertex parents ie 运行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);
}

And then method to get shortest path will look like this 然后获得最短路径的方法将如下所示

   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);
        }
    }
}

Explanation of shortestPath above 上面的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;

Thanks Fafore I alredy solved it. 谢谢Fafore,我已经解决了。 What I did was to set all adjacent nodes to the end vertex and store them in a stack while they were different to start the vertex. 我要做的是将所有相邻节点设置为最终顶点,并将它们存储在堆栈中,而它们之间的区别在于开始顶点不同。 And then I made a while until the stack were empty and started checking which one was adjacent to start vertex and then which one were adjacent between them (as the first one of the stack is adjacent to end vertex) and then add the ones adjacents to a queue. 然后我花了一段时间,直到堆栈为空,然后开始检查哪个堆栈与起始顶点相邻,然后检查哪个堆栈彼此相邻(因为堆栈的第一个与结束顶点相邻),然后将相邻的相加到一个队列。 It didn't relly needed to be shortest path, but thanks =) 它不一定非要成为最短路径,但谢谢=)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM