最小生成树

Posted 枝枝

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了最小生成树相关的知识,希望对你有一定的参考价值。

//最小生成树:prim法则
void prim(vector<vector<int>> &graph, vector<bool> &visited)
{
	stack<int> mys;
	int mark = 255;
	int x = 0, y = 0;
	for (int i = 0; i < graph.size(); i++)
	{
		for (int j = 0; j < graph[i].size(); j++)
		{
			if (graph[i][j] < mark && graph[i][j] != 0)
			{
				mark = graph[i][j];
				x = i;
				y = j;
			}
		}
	}
	visited[x] = true;
	visited[y] = true;
	mys.push(x);
	mys.push(y);
	cout << x+1 << "---->";
	cout << y+1 << "---->";
	mark = graph.size() - 2;
	int count = 0;
	while (mark-- && !mys.empty())
	{
		int data = 255;
		for (int i = 0; i < graph[y].size(); i++)
		{
			if (graph[y][i] < data && visited[i] == false)
			{
				data = graph[y][i];
				count = i;
				mys.push(count);
			}
		}
		if (data != 255)
		{
			cout << count+1 << "---->";	
			visited[count] = true;
			y = count;
		}	
		else
		{
			y = mys.top();
			mys.pop();
		}
	}
}

int main()
{
	int n = 6;
	vector<vector<int>>  graph(n, vector<int>(n));
	vector<bool> visited(graph.size());
	for (int i = 0; i < visited.size(); i++)
	{
		visited[i] = false;
	}
	graph[0] = { 0, 6, 1, 5, 0, 0 };
	graph[1] = { 6, 0, 5, 0, 3, 0 }; 
	graph[2] = { 1, 5, 0, 5, 6, 4 };
	graph[3] = { 5, 0, 5, 0, 0, 2 };
	graph[4] = { 0, 3, 6, 0, 0, 6 };
	graph[5] = { 0, 0, 4, 2, 6, 0 };
	show_graph(graph);
	cout << endl;
	DFS_digui(graph, visited, 0);
	cout << endl;
	for (int i = 0; i < visited.size(); i++)
	{
		visited[i] = false;
	}
	BFS(graph, visited, 0);
	cout << endl;
	for (int i = 0; i < visited.size(); i++)
	{
		visited[i] = false;
	}
	prim(graph, visited);
	system("pause");
	return 0;
}

  

以上是关于最小生成树的主要内容,如果未能解决你的问题,请参考以下文章

最小生成树matlab代码Kruskal算法,用于二维网络生成

c语言最小生成树

最小生成树及Prim算法及Kruskal算法的代码实现

数据结构 图连通与最小生成树

次最小生成树 模版

图的最小生成树算法(图解+代码)| 学不会来看我系列