1、构建邻接多重表
2、首先编写函数BFSTraverse(OLGraph &G, int start),BFS广度优先搜索打印出来结果,防止后续在求距离时顺序出现问题
3、在广度优先遍历的函数中添加一个变量end,这样就可以通过start和end确定两点
完整代码如下:
#include "pch.h"
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <cassert>
#include <vector>
#include <stack>
#include <queue>
using namespace std;
#define INFINITY 2147483647
#define MAX_VEX 30
typedef int InfoType;
typedef int VexType;
typedef struct ArcNode
{
int tailvex, headvex; // 尾结点和头结点在图中的位置
InfoType weight;
struct ArcNode *hlink, *tlink;
}ArcNode; //弧结点类型定义
typedef struct VexNode
{
VexType data;
ArcNode *firstout=NULL;
}VexNode; //顶点结点类型定义
typedef struct
{
int vexnum;
VexNode xlist[MAX_VEX];
}OLGraph; //图的类型定义
//建立顶点表
void AddVex(OLGraph *G)
{
int i;
for (i = 0; i < G->vexnum; i++)
{
G->xlist[i].data = i;
G->xlist[i].firstout = NULL;
}
}
//给点v1和点v2建立一条权重为cost的边
void AddArc(OLGraph *G, int v1, int v2, int cost)
{
ArcNode *pArc = new ArcNode;
pArc->headvex = v1;
pArc->tailvex = v2;
pArc->weight = cost;
pArc->hlink = G->xlist[v1].firstout;
pArc->tlink = G->xlist[v2].firstout;
G->xlist[v1].firstout = pArc;
G->xlist[v2].firstout = pArc;
}
void InitMap(OLGraph &map)
{
map.vexnum = 5; //初始化图的顶点数目
AddVex(&map); //为该图建立4个点
AddArc(&map, 0, 1, 1); //为该图建立3条权值为1的边
AddArc(&map, 0, 2, 2);
AddArc(&map, 1, 3, 1);
AddArc(&map, 0, 3, 4);
}
void BFSTraverse(OLGraph &G, int start,int end)
{
int i;
bool visited[100];
int distance[100];
for (i = 0; i < G.vexnum; i++) {
visited[i] = false; //辅助访问标志数组初始化
distance[i] = -1;
}
ArcNode *tmp = G.xlist[start].firstout;
for (i = 0; i < G.vexnum; i++)
{
if (!visited[start]) //尚未访问
{
visited[start] = true; //设置访问标志
//cout << G.xlist[start].data << " "; //访问输出该点的数据
queue<int> q; //置空的辅助队列Q
ArcNode *p;
int pos;
q.push(start); //入队列
while (!q.empty()) //当队非空
{
pos = q.front(); //队头元素出队并置为pos
q.pop();
p = G.xlist[pos].firstout; //p指向依附于顶点pos的第一条边
while (p)
{
if (p->headvex == start) {
distance[p->tailvex] = p->weight;
}
else if (p->tailvex == start) {
distance[p->headvex] = p->weight;
}
else if (distance[p->headvex] != -1) {
if (distance[p->headvex] + p->weight < distance[p->tailvex])
distance[p->tailvex] = distance[p->headvex] + p->weight;
}
else if (distance[p->tailvex] != -1) {
if (distance[p->tailvex] + p->weight < distance[p->headvex])
distance[p->headvex] = distance[p->tailvex] + p->weight;
}
if (p->headvex == pos) //如果顶点pos就是该边的头结点
{
if (!visited[p->tailvex]) //如果该边的尾结点未访问
{
visited[p->tailvex] = true; //设置访问标志
//cout << G.xlist[p->tailvex].data << " "; //访问输出该尾结点的数据
q.push(p->tailvex); //该尾结点点入队列
}
p = p->hlink; //p沿hlink(path1)移动
}
else //如果顶点pos就是该边的尾结点
{
if (!visited[p->headvex]) //如果该边的头结点未访问
{
visited[p->headvex] = true; //设置访问标志
//cout << G.xlist[p->headvex].data << " "; //访问输出该头结点的数据
q.push(p->headvex);//该头结点点入队列
}
p = p->tlink; //p沿tlink(path2)移动
}
}
}
}
}
cout << distance[end];
cout << endl << endl;
}
int main() {
OLGraph Head;
InitMap(Head);
BFSTraverse(Head, 0,3);
return 0;
}