视频地址: https://www.bilibili.com/video/av25763384/?spm_id_from=333.788.videocard.0
最短路径
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
#include<vector>
#include<map>
using namespace std;
void shortest_path(map<char, vector<char>>graph, char s)
{
vector<char>queue, seen;
queue.push_back(s);
seen.push_back(s);
map <char, char> parent
{
{s,0}
};
char vertex;
while (queue.size() > 0)
{
vertex = queue.front();
queue.erase(queue.begin());
vector <char> nodes = graph[vertex];
for (char w : nodes)
{
auto ret = find(seen.begin(), seen.end(), w);
if (ret == seen.end())
{
queue.push_back(w);
seen.push_back(w);
parent[w] = vertex;
}
}
printf("%c ", vertex);
}puts("");
char v = 'F';
while (v != 0)
{
printf("%c ", v);
v = parent[v];
}puts("");
}
int main(void)
{
vector<char> a{ 'B', 'C' };
vector<char> b{ 'A', 'C', 'D' };
vector<char> c{ 'A', 'B', 'D','E' };
vector<char> d{ 'B', 'C', 'E','F' };
vector<char> e{ 'C', 'D' };
vector<char> f{ 'D' };
map <char, vector<char>> graph
{
{ 'A',a },{ 'B',b },{ 'C',c },{ 'D',d },{ 'E',e },{ 'F',f }
};
shortest_path(graph, 'A');
system("pause");
return 0;
}