这个是我在coursera.org上学习 C++ For C Programmers 课程的一个作业。用C++面向对象来写算法,这增加了我对面向对象的理解。
方法为:
1、创建一个class类
2、定义私有数据成员
3、定义各种方法来对私有数据进行操作
代码如下:
#include <iostream>
#include <queue>
#define maxx 999999 //dustance infinity
using namespace std;
class Node
{
public:
void Initialize();
void deletemessage();
void InputNodenum(int num); //input node's number
void InputMess(int i, int j, int distance); //input i to j distance
int Dijkstra(int star, int endnode); //Dijkstra algorithm
private:
int nodenum; //node's quantity
int digraph[200][200]; //'maxx' con't
int min_distance[200]; //The shortest distance
int sign[200]; //Whether to enter the queue,'0' is no, '1' is yes
int distance; //star to now's distance
};
void Node::Initialize()
{
int i,j;
for(i = 0; i < 200; i++)
{
sign[i] = 0; //all node not enter the queue
min_distance[i] = maxx; //the distance that star to all node is 'maxx'
for(j = 0; j < 200; j++)
{
digraph[i][j] = maxx;
}
}
return ;
}
void Node::deletemessage()
{
int i;
for(i = 0; i < nodenum; i++)
{
sign[i] = 0;
min_distance[i] = maxx;
}
}
void Node::InputNodenum(int num)
{
nodenum = num;
return ;
}
void Node::InputMess(int i, int j, int distance)
{
digraph[i][j] = distance; //input distance
digraph[j][i] = distance;
return ;
}
int Node::Dijkstra(int star, int endnode)
{
int now; //now node
int next; //next node
int newdis; //new distance
queue<int> q;
q.push(star); //star enter the queue
min_distance[star] = 0; //update star's distance
while(!q.empty()) //this is BFS(Breadth First Search)
{
now = q.front();
q.pop();
sign[now] = 1; //sign 'now' is enter the queue
for(next = 0; next < nodenum; next++)
{
if(digraph[now][next]!=maxx && sign[next] == 0) //if now to next is link and next not enter queue, then next need enqueue
{
q.push(next);
newdis = min_distance[now] + digraph[now][next]; //compute star to next node's distance
if(newdis < min_distance[next]) //update next node's min_distance
{
min_distance[next] = newdis;
}
}
}
}
return min_distance[endnode];
}
int main()
{
int a,b,distance,num;
int pathnum; //the path of number
int star,endnode;
int min_distance;
Node *node= new Node();
node->Initialize();
cout<<"please input node's number(no more than 200) and the number of path:"<<endl;
cout<<"node's number: ";
cin>>num;
cout<<"path's number: ";
cin>>pathnum;
node->InputNodenum(num);
cout<<"please input node's information(a b distance) node's number is 0 to num-1"<<endl;
for(int i = 0; i < pathnum; i++)
{
cin>>a>>b>>distance;
node->InputMess(a,b,distance);
}
cout<<"please input star and end(end of EOF):"<<endl;
while(cin>>star>>endnode)
{
node->deletemessage();
min_distance = node->Dijkstra(star,endnode);
if(min_distance == maxx)
{
cout<<"no path"<<endl;
}
else
{
cout<<"the short distance is: "<<min_distance<<endl;
}
}
return 0;
}