简体   繁体   中英

BFS shortest path only using adjacency matrix?

I'm trying to implement Ford-Fulkerson/Edmonds-Karp only using adjacency matrix'. The only thing I'm not able to program is the function to calculate the shortest path, using BFS. The function to see if a shortest path actually exists is fine, but is it possible to also get the shortest path? Or is the only way to get the shortest path with BFS to use some kind of parent pointers, and traverse backwards to get the path?

Here is my code for see if path exists:

public static boolean existsPathFromSourceToSinkInGf(int Gf[][])
{
    LinkedList<Integer> queue = new LinkedList<Integer>();
    queue.add(0);

    while (!queue.isEmpty())
    {
        int v = queue.remove();
        if (v == sink) return true;
        for (int i = 0; i < 5; i++)
        {

            if (Gf[v][i] != 0)
            {
                if (!queue.contains((Integer)i))
                {
                    queue.add((Integer)i); 
                }
            }
        }
    }

    return false;

  }

The common way to do it would indeed be to maintain parent pointers each time you settle a node and to go backwards once you found your path.

You could also keep track of paths explicitly in your queue. Instead of using just an integer for your linkedlist, you could create your own class consisting of the integer and a string with something like "node 1-> node 3->...". It's less commonly used because of the overhead of the class and the paths, but it avoids having to keep the parent pointers on their own and having to traverse them in the end.

On a side note 2 remarks on your code:

  1. Why does it run for i=0..5?
  2. You check if (!queue.contains((Integer)i)) so you don't put a vertex on your queue that's already on it. You should also avoid putting vertices on that have already been removed from the list (try maintaining a set of visited nodes).

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