我的程序正在按照
的顺序从文本文件中读取输入A
B
C
A B 10
A C 5
B A 3
B C 2
C A 4
C B 1
并将数据存储到由邻接列表表示的图形中。我想编写一个程序,使用Dijkstra算法找到从A到所有其他节点的最短路径。
我观看了几个视频,但仍然无法完全了解如何实现算法,因为示例使用的图形表示为邻接矩阵。以下是该计划:
#include <cstdlib>
#include <iostream>
#include <fstream>
#include <locale>
#include <sstream>
#include <string>
#include <vector>
using namespace std;
#define INFINITE -1
/* node */
struct Node
{
char key;
int distance;
Node *next;
};
/* GraphNode */
struct GraphNode
{
char key;
Node *listpointer;
};
/* Add nodes to the front of the list */
void AddNodeToFront(Node*& listpointer, char newkey, int newdistance)
{
Node *temp;
temp = new Node;
temp->key = newkey;
temp->distance=newdistance;
temp->next = listpointer;
listpointer = temp;
}
/* printf LLnodes */
void PrintLLnodes(Node*& listpointer)
{
Node *temp;
temp = listpointer;
while(temp!=NULL)
{
printf("to node %c dist: %d \n", temp->key, temp->distance);
temp=temp->next;
}
}
/* Implement the Graph class */
class Graph
{
private:
vector<GraphNode> adjlist;
int totalgraphnodes;
public:
Graph(){totalgraphnodes = 0;}
~Graph(){}
void AddNewGraphNode(char newgraphnode);
void AddNewEdgeBetweenGraphNodes(char A, char B, int distance);
void PrintAllGraphNodesWithCosts();
void DijkstrasAlgorithm(char sourcenode);
int GetTotalNodes() { return totalgraphnodes; }
};
/* graph class functions */
void Graph::AddNewGraphNode(char newgraphnode){
totalgraphnodes++;
GraphNode temp;
temp.key=newgraphnode;
temp.listpointer = NULL;//important
adjlist.push_back(temp);
}
void Graph::AddNewEdgeBetweenGraphNodes(char A, char B, int distance)
{
//find which node A is
int a;
for (a = 0;adjlist.size();a++)
{
if (A == adjlist[a].key) break;
}
AddNodeToFront(adjlist[a].listpointer, B, distance);
}
void Graph::PrintAllGraphNodesWithCosts()
{
for (unsigned int a = 0;a < adjlist.size();a++){
printf("From Node %c: \n", adjlist[a].key);
PrintLLnodes(adjlist[a].listpointer);
}
}
**// implement Dijkstra's Algorithm
void Graph::DijkstrasAlgorithm(char sourcenode)**
{
int distance[adjlist.size()];
char state[adjlist.size()];
// setting the initial distance and state of the first node
distance[0] = 0;
state[0] = 'p';
// assigning all distance and state to temp and infinite
for(int i = 1; i <= adjlist.size(); i++)
{
distance[i] = INFINITE;
state[i] = 't';
}
// get the sourcenode from the adjlist in Graph
unsigned int a;
for(a = 0; a <= adjlist.size(); a++)
{
if(sourcenode == adjlist[a].key) { break; } // break when found 'A'
}
// assign sourcenode listpointer to current
Node *current;
current = adjlist[a].listpointer;
bool stilltempvertex = true;
while(stilltempvertex) {}
}
/* declare a new Graph */
Graph mygraph;
main( /*int argc, char** argv */)
{
/* call Dijkstra */
mygraph.DijkstrasAlgorithm('A'); //always from A in this program
/* Print answer in the required format */
}
就实现而言,所有节点和边缘都被正确读取(我已经省略了一些代码以允许可读性,但mygraph有节点A,B,C和相应的边缘。),它只是我不能似乎弄清楚如何正确实现这个算法。
从文件中读取节点并将其存储在向量ajdlist中。然后,每个graphnode都有自己的链表,指向图中的相邻节点。
任何人都可以带我逐步完成算法实现吗?提前谢谢。