How to modify dijkstra algorithm to find all possible paths?

If you want to find all simple paths, than use modified BFS (you will remember used vertices in order not to repeat them in the path). Finding of all paths might not be even possible (the procedure will not terminate (i.e. it is not an algorithm)). Just imagine graph with cycle, there are infinite paths between all nodes (differing in number of loops contained...)


You can not easily modify Dijkstra to show you all the possible paths. You need to modify the BFS or DFS search.

If you try to modify Dijkstra, in the end, you will end with a BFS or DFS search algorithm, so best start from there instead.


OK, I have actually modified Dijkstra class to do BFS as well and it got me all possible routes. I added this method:

public void BreadthFirst(Edge graph, LinkedList<String> visited) 
{
    LinkedList<String> nodes = graph.adjacentNodes(visited.Last());

    // Examine adjacent nodes
    foreach (String node in nodes) 
    {
        if (visited.Contains(node))
        {
            continue;
        }

        if (node.Equals(endNode))
        {
            visited.AddLast(node);

            printPath(visited);

            visited.RemoveLast();

            break;
         }
     }

    // In breadth-first, recursion needs to come after visiting adjacent nodes
    foreach (String node in nodes)
    {      
        if(visited.Contains(node) || node.Equals(endNode))
        {
            continue;
        }

        visited.AddLast(node);

        // Recursion
        BreadthFirst(graph, visited);

        visited.RemoveLast();
    }
}

Usage would be like this:

Dijkstra d = new Dijkstra(_edges, _nodes);

LinkedList<String> visited = new LinkedList<string>();  //collecting all routes
visited.AddFirst(start);

d.BreadthFirst(graph, visited);