简体   繁体   中英

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).

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. My bfs method:

    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

    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

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. 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 =)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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