如何修改Disjktra算法以在最短路径中至少包含X个顶点或K个边

时间:2019-04-27 00:55:08

标签: c++ algorithm c++11 data-structures dijkstra

我有这个Dijkstra算法,尽管我想对其进行修改,或者可以使用其他算法来实现它?

我需要输出最短路径的顶点,尽管我需要至少5个顶点(> = 5个顶点)到从起始节点到结束节点的最短路径。

在代码结尾,您将看到Dijkstra算法,因此我需要对其进行修改,以便在需要至少具有X(在我的情况下为5个)顶点的地方添加一个变量。

#include<iostream>
#include<set>
#include<list>
#include<algorithm>

using namespace std;

typedef struct nodes {
        int dest;
        double cost;
}node;
class Graph{

    int n;


   list<node> *adjList;

   private:
      void showList(int src, list<node> lt) {
         list<node> :: iterator i;
         node tempNode;

         for(i = lt.begin(); i != lt.end(); i++) {
            tempNode = *i;
            cout << "(" << src << ")---("<<tempNode.dest << "|"<<tempNode.cost<<") ";
         }
         cout << endl;
      }
   public:
      Graph() {
         n = 0;
      }

      Graph(int nodeCount) {
         n = nodeCount;
         adjList = new list<node>[n];
      }

      void addEdge(int source, int dest, double cost) {
         node newNode;
         newNode.dest = dest;
         newNode.cost = cost;
         adjList[source].push_back(newNode);
      }

      void displayEdges() {
         for(int i = 0; i<n; i++) {
            list<node> tempList = adjList[i];
            showList(i, tempList);
         }
      }

      friend void dijkstra(Graph g, double *dist, int *prev, int start);
};

void dijkstra(Graph g, double *dist, int *prev, int start) {
   int n = g.n;

   for(int u = 0; u<n; u++) {
      dist[u] = 9999;   //set as infinity
      prev[u] = -1;    //undefined previous
   }

   dist[start] = 0;   //distance of start is 0
   set<int> S;       //create empty set S
   list<int> Q;

   for(int u = 0; u<n; u++) {
      Q.push_back(u);    //add each node into queue
   }

   while(!Q.empty()) {
      list<int> :: iterator i;
      i = min_element(Q.begin(), Q.end());
      int u = *i; //the minimum element from queue
      Q.remove(u);
      S.insert(u); //add u in the set
      list<node> :: iterator it;

      for(it = g.adjList[u].begin(); it != g.adjList[u].end();it++) {
         if((dist[u]+(it->cost)) < dist[it->dest]) { //relax (u,v)
            dist[it->dest] = (dist[u]+(it->cost));
            prev[it->dest] = u;
         }
      }
   }
}

谢谢您的帮助

0 个答案:

没有答案