最短路径
本文介绍求最短路径,但不是Dijkstra算法和Bellman-ford算法求有向图中一点到其余各点的最短路径,而是求解有向图中指定两点的最短路径。
方法很简单,建立与BFS之上,因此我们只需要修改队列中的内容。
这里本来该有图的,但是最近忙专业课,下回补上!
typedef struct QNode{
int pos;
VertexType data;
struct QNode *prior;
struct QNode *next;
}QNode;
具体算法如下:(PS:最后输出的答案是反向的,可以利用一个栈或者数组反向输出都行)
#include <iostream>
#include <malloc.h>
using namespace std;
#define VRType int
#define VertexType char
#define MAX_VERTEX_NUM 30
typedef struct{
VertexType vexs[MAX_VERTEX_NUM];
VRType edges[MAX_VERTEX_NUM][MAX_VERTEX_NUM];
int vexnum,arcnum;
}MGraph;
void CreatMGraph(MGraph &G)
{
cin>>G.vexnum;
for(int i = 0; i < G.vexnum; i++)
cin>>G.vexs[i];
for(i = 0; i < G.vexnum; i++)
for(int j = 0; j < G.vexnum; j++)
cin>>G.edges[i][j];
}
typedef struct QNode{
int pos;
VertexType data;
struct QNode *prior;
struct QNode *next;
}QNode;
typedef struct{
QNode *front;
QNode *rear;
}LiQueue;
void InitQueue(LiQueue *&Q)
{
Q = (LiQueue *) malloc (sizeof(LiQueue));
Q->front = Q->rear = NULL;
}
bool EmptyQueue(LiQueue *Q)
{
if((!Q->front) || (!Q->rear))
return true;
else return false;
}
void EnQueue(LiQueue *&Q, MGraph G, int n, QNode *q)
{
QNode *p;
p=(QNode *) malloc (sizeof(QNode));
p->data = G.vexs[n];
p->pos = n;
p->prior = q;
p->next = NULL;
if(EmptyQueue(Q))
Q->front = Q->rear = p;
else{
Q->rear->next = p;
Q->rear = p;
}
}
void DeQueue(LiQueue *&Q, QNode *&p)
{
if(!EmptyQueue(Q)){
p = Q->front;
Q->front = Q->front->next;
}
}
int visit[MAX_VERTEX_NUM]={0};
void ShortestPath(MGraph G,VertexType start,VertexType end)
{
LiQueue *Q;
QNode *p;
InitQueue(Q);
for(int i = 0; i < G.vexnum; i++)
if(G.vexs[i] == start)
break;
EnQueue(Q, G, i, NULL);
visit[i] = 1;
while(!EmptyQueue(Q)){
DeQueue(Q,p);
if(p->data == end)
break;
for(i = 0; i < G.vexnum; i++)
if(G.edges[p->pos][i] && !visit[i]){
visit[i] = 1;
EnQueue(Q, G, i, p);
}
}
while(p){
cout<<p->data;
p = p->prior;
}
cout<<endl;
}
int main()
{
char start,end;
MGraph g;
CreatMGraph(g);
cin>>start>>end;
ShortestPath(g,start,end);
return 0;
}