一个 恋爱关系图
胡图图love:98于小美
胡图图love:48何壮壮
胡图图love:99小怪
于小美love:10张帅子
何壮壮love:45张帅子
小怪love:100张帅子
胡图图到张帅子的最短路径
确定不是恋爱路径?
算法实现
先看猛料再看是否实现思路
// 定义深度优先搜索状态
struct DepthFirstSearchFLag {
int index; // 当前索引
bool visited[MaxSize]; // 顶点访问状态
};
// 定义最短路径状态
struct ShortPathFLag {
DepthFirstSearchFLag Flag; // 深度优先搜索状态
int end; // 结束顶点索引
int stepNum; // 步数
int m_Weight; // 当前路径权重
int ArgsWeight; // 参数路径权重
int SevePath[MaxSize]; // 保存路径
int ShortPathValue[MaxSize];// 最短路径值
};
void ShortPath(const Graph& graph, ShortPathFLag &ShortPathFLag) {
int& index = ShortPathFLag.Flag.index;
int& end = ShortPathFLag.end;
auto& visited = ShortPathFLag.Flag.visited;
auto& SevePath = ShortPathFLag.SevePath;
auto& ShortPaths = ShortPathFLag.ShortPathValue;
int& stepNum = ShortPathFLag.stepNum;
int& ArgsWeight = ShortPathFLag.ArgsWeight;
int& Weight = ShortPathFLag.m_Weight;
if (index==end){
for (size_t i = 0; i < stepNum; i++) {
cout << graph.List[SevePath[i]]->value << " ->"; //输出路径
}
cout <<"\t该路径对应的恋爱值 (Love)是:" << ArgsWeight << endl; // 输出对应路径长度
if (Weight < ArgsWeight){
Weight = ArgsWeight;
int conut = stepNum * sizeof(conut);
memcpy(ShortPaths, SevePath, conut);
ArgsWeight = 0;
}
}
int currentIndex = index;
visited[index] = true;
Edge* current = graph.List[index]->First;
while (current) {
currentIndex = current->AdjVertex;
if (!visited[currentIndex]){
visited[currentIndex] = true;
int currentWeight = current->Weight;
SevePath[stepNum++] = currentIndex;
ArgsWeight = ArgsWeight + currentWeight;
index = currentIndex;
ShortPath(graph, ShortPathFLag);
visited[currentIndex] = false;
SevePath[--stepNum] = 0;
}
current = current->next;
}
}
void ShortPath(const Graph& graph, VertexValue VertexValueFirst, VertexValue VertexValueSecond){
ShortPathFLag Flag{};
Flag.m_Weight = 0;
const int VertexSize = graph.VertexSize;
Flag.Flag.index = Location(graph, VertexValueFirst);
Flag.end = Location(graph, VertexValueSecond);
if (Flag.Flag.index != VertexSize && Flag.end!= VertexSize) {
cout << VertexValueFirst << "到" << VertexValueSecond << "最短路径:" << endl;
ShortPath(graph, Flag);
cout << endl;
cout << VertexValueFirst << "到" << VertexValueSecond << "最短路径为恋爱总值:" << Flag.m_Weight << endl;
cout << "路径:"<< VertexValueFirst<<" ";
auto& Path = Flag.ShortPathValue;
int i = 0;
while (i < MaxSize && Path[i]>0) {
cout <<"-> " << graph.List[Path[i]]->value << " ";
i++;
}
cout << endl;
}
}
算法思想
最短路径算法图
递归调用
返回上一层递归
结果