All the paths between 2 nodes in graph

后端 未结 4 1027
迷失自我
迷失自我 2021-01-19 03:06

I have to make an uninformed search (Breadth-first-Search) program which takes two nodes and return all the paths between them.

public void BFS(Nod start, N         


        
4条回答
  •  旧巷少年郎
    2021-01-19 03:37

    Sounds like homework. But the fun kind.

    The following is pseudocode, is depth first instead of breath first (so should be converted to a queue type algorithm, and may contain bugs, but the general jist should be clear.

    class Node{
      Vector[Link] connections;
      String name;
    }
    
    class Link{
      Node destination;
      int distance;
    }
    
    Vector[Vector[Node]] paths(Node source, Node end_dest, Vector[Vector[Node]] routes){
      for each route in routes{
        bool has_next = false;
        for each connection in source.connections{
          if !connection.destination in route {
            has_next = true;
            route.push(destination);
            if (!connection.destination == end_dest){
              paths(destination, end_dest, routes);
            }
          }
        }
        if !has_next {
          routes.remove(route) //watch out here, might mess up the iteration
        }
      }
      return routes;
    }
    

    Edit: Is this actually the answer to the question you are looking for? Or do you actually want to find the shortest path? If it's the latter, use Dijkstra's algorithm: http://en.wikipedia.org/wiki/Dijkstra%27s_algorithm

提交回复
热议问题