左神基础课 - 拓扑排序

遍历图中的所有节点,把其入度为零的节点先入队

然后进入循环,每次出队一个元素,把该元素所指向节点的入度减1,当发现对应节点减完1后入度为零,则入队

list sortedTopology(Graph graph){
	unordered_map inMap;
	queue queue;
	unordered_map::iterator ite = graph.nodes.begin();
	//遍历图中的所有节点,把其入度为零的节点先入队
	while(ite != graph.nodes.end()){
		inMap[ite->second] = ite->second->in;
 		if(ite->second->in == 0){
			queue.push(ite->second);
		}
		ite++;
	}
	list list;
	Node* help;
	//循环中,每次出队一个元素,把该元素所指向节点的入度减1,当发现对应节点减完1后入度为零,则入队
	while(!queue.empty()){
		help = queue.front();
		queue.pop();
		list.push_back(help);
		// cout << " " << help->value << endl;
		for(auto node : help->next){
			inMap.find(node)->second = (inMap.find(node)->second -1);
			if(inMap.find(node)->second  == 0)
				queue.push(node);
		}
	}
	return list;
}

 

 

总的代码:

#include
#include
#include
#include
#include
#include
using namespace std;
//解依赖
class Edge;
class Node{
public:
	int value;
	int in;
	int out;
	list next;
	list edges;
	Node(int value){
		this->value = value;
		in = 0;
		out =0;
	}
};
class Edge{
public:
	int weight;
	Node* from;
	Node* to;

	Edge(int weight,Node* from, Node* to){
		this->weight = weight;
		this->from = from;
		this->to = to;
	}
};
class Graph{
public:
	unordered_map nodes;
	unordered_set edges;

};
class GraphGenerator{
public:
	Graph createGraph(int matrix[][3],int rows, int col){
		Graph graph;
		for(int i=0;isecond;
			Node* toNode = graph.nodes.find(to)->second;
			//为 graph 和 from所在的node 准备 一条边
			Edge* newEdge = new Edge(weight, fromNode, toNode);
			//对于新增的一条边, 被指向节点的入度+1
			toNode->in++;
			//对于新增的一条边, 指向节点的出度+1,所指向的节点确定,指向该节点的边确定
			fromNode->out++;
			fromNode->next.push_back(toNode);
			fromNode->edges.push_back(newEdge);
			//两个if会保证建立节点,这里保证 边的存在。
			graph.edges.insert(newEdge);

		}
		return graph;
	}
};

list sortedTopology(Graph graph){
	unordered_map inMap;
	queue queue;
	unordered_map::iterator ite = graph.nodes.begin();
	//遍历图中的所有节点,把其入度为零的节点先入队
	while(ite != graph.nodes.end()){
		inMap[ite->second] = ite->second->in;
 		if(ite->second->in == 0){
			queue.push(ite->second);
		}
		ite++;
	}
	list list;
	Node* help;
	//循环中,每次出队一个元素,把该元素所指向节点的入度减1,当发现对应节点减完1后入度为零,则入队
	while(!queue.empty()){
		help = queue.front();
		queue.pop();
		list.push_back(help);
		// cout << " " << help->value << endl;
		for(auto node : help->next){
			inMap.find(node)->second = (inMap.find(node)->second -1);
			if(inMap.find(node)->second  == 0)
				queue.push(node);
		}
	}
	return list;
}

int main(){
	GraphGenerator g;
	// int matrix[][3]= {{1,1,2},{2,2,3},{3,3,1}};
	int matrix[][3]={{0,1,2},{0,1,3},{0,1,4},{0,2,3},{0,2,7},{0,7,3},
				{0,3,5},{0,4,6}};
	int length = sizeof(matrix)/sizeof(matrix[0]);
	Graph graph = g.createGraph(matrix, length,3);
	Node* node = graph.nodes.find(1)->second;
	list list = sortedTopology(graph);
	std::list::iterator ite = list.begin();
	while(ite != list.end()){
		cout << (*ite)->value<

 

你可能感兴趣的:(左神基础班代码,C++)