最小生成树

//最小生成树: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;
}

  

posted on 2016-09-22 12:24  枝枝  阅读(99)  评论(0编辑  收藏  举报