首页 > 其他 > 详细

看正月点灯笼老师的笔记—BFS和DFS ( 2 )

时间:2020-03-07 10:19:36      阅读:50      评论:0      收藏: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;
}

  

看正月点灯笼老师的笔记—BFS和DFS ( 2 )

原文:https://www.cnblogs.com/asdfknjhu/p/12432059.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!