const Infinity = -1;//标识 无穷大 const MaxVexNum = 50;//最大定点个数 typedef string VexType; typedef int ArcType; typedef struct ArcNode { int adjvex;//弧头节点序号 ArcType info;//弧权值信息 ArcNode *nextarc; }*ArcPtr; struct VexNode { VexType data; ArcPtr firstarc; int x,y; }; struct ALGraph { VexNode vexs[MaxVexNum + 1]; int vexnum,arcnum; }; class CGraph { public: CGraph(); virtual ~CGraph(); int LocateVex(VexType v); //寻找结点位置 void CreateGraph(CLink &link_Node,CLink &link_weight);//创建图 link_Node为节点链表,其结点的第二个值为空 link_weight为权值链表 bool ShortPath_Dijkatral(VexType v,int distance[]); bool Less(ArcType x,ArcType y); bool Less(ArcType x,ArcType y,ArcType z); private: ALGraph G; }; bool CGraph::Less(ArcType x,ArcType y) { return x != Infinity && (y == Infinity || x <y); } bool CGraph::Less(ArcType x,ArcType y,ArcType z) { return x != Infinity && y != Infinity && (z == Infinity || x+y <z); } //迪杰斯特拉算法 bool CGraph::ShortPath_Dijkatral(VexType v,int distance[]) { int i,j,k,s,t,w,r= Infinity; bool found[MaxVexNum+1]; ArcPtr p; int d[MaxVexNum+1]; VexType path[MaxVexNum+1][MaxVexNum+1]; int vn[MaxVexNum+1]; for(i = 0;i< MaxVexNum+1;i++) { d[i] =0; } s = LocateVex(v); if(s == 0)return false; for(i =1;i<= G.vexnum;i++) { for (p = G.vexs[s].firstarc;p;p= p->nextarc) { w = p->adjvex; if(w == i)d[i] = p->info; } if (d[i] == 0)d[i] = Infinity; found[i] = false; path[i][1] = G.vexs[s].data; path[i][2] = G.vexs[i].data; vn[i] = 2; } d[s] = 0; found[s] = true; for ( k =1;k<= G.vexnum -1;k++)//寻找从该点到其他点的距离 { j = 0; for (i = 1;i<= G.vexnum;i++) if(!found[i] && (j == 0 || Less(d[i],d[j])))j = i; found[j] = true; for (i =1;i<= G.vexnum;i++) { for (p = G.vexs[j].firstarc;p;p = p->nextarc) { w = p->adjvex; if(w == i){r = p->info;break;} else r =Infinity; } if(!found[i] && Less(d[j],r,d[i])) { d[i] = d[j] + r; for (t =1;t<= vn[j];t++) path[i][t] = path[j][t]; vn[i] = vn[j] +1; path[i][vn[i]] = G.vexs[i].data; } } } for (i =1;i<= G.vexnum;i++) { distance[i] = d[i]; } return true; } //寻找节点序号 int CGraph::LocateVex(VexType v) { int i; for (i = G.vexnum;i > 0 && G.vexs[i].data != v;i--); return i; }