图的拓扑序列(BFS)

way:找入度为0的节点删除,减少其他节点的入度,继续找入度为0的节点,直到删除完所有的图节点。(遍历node的neighbors就能得到neighbors的入度信息)

cpp 复制代码
#include<iostream>
#include<vector>
#include<map>
#include<queue>
using namespace std;


class Node {
public:
	int label;
	vector<Node*> neighbors;
	Node(int x)
	{
		label=x;
	}
};


vector<Node*> topSort(vector<Node*> graph)
{
	map<Node*, int>indegreeMap;
	//统计所有节点的入度信息到indegreeMap中
	for(auto node: graph)
	{
		indegreeMap[node]=0;
	}

	for(auto node: graph)
	{
		for(auto next: node->neighbors)
		{
			indegreeMap[next] = indegreeMap[next]+1;
		}
	}

	//将入度为0的节点放入zeroQue中
	queue<Node*> zeroQue;
	for(auto pa: indegreeMap)
	{
		if(pa.second == 0)
		{
			zeroQue.push(pa.first);
		}
	}

	vector<Node*> result;

	//开始删除节点,减少入度
	while(!zeroQue.empty())
	{
		Node *cur = zeroQue.front();
		zeroQue.pop();
		result.push_back(cur);
		for(auto next: cur->neighbors)
		{
			indegreeMap[next] = indegreeMap[next]-1;
			if(indegreeMap[next]==0)
			{
				zeroQue.push(next);
			}
		}
	}
	return result;
}
相关推荐
huapiaoy18 分钟前
Redis中数据类型的使用(hash和list)
redis·算法·哈希算法
冷白白31 分钟前
【C++】C++对象初探及友元
c语言·开发语言·c++·算法
鹤上听雷39 分钟前
【AGC005D】~K Perm Counting(计数抽象成图)
算法
一叶祇秋1 小时前
Leetcode - 周赛417
算法·leetcode·职场和发展
武昌库里写JAVA1 小时前
【Java】Java面试题笔试
c语言·开发语言·数据结构·算法·二维数组
ya888g1 小时前
GESP C++四级样题卷
java·c++·算法
Funny_AI_LAB1 小时前
MetaAI最新开源Llama3.2亮点及使用指南
算法·计算机视觉·语言模型·llama·facebook
NuyoahC2 小时前
算法笔记(十一)——优先级队列(堆)
c++·笔记·算法·优先级队列
jk_1012 小时前
MATLAB中decomposition函数用法
开发语言·算法·matlab
penguin_bark2 小时前
69. x 的平方根
算法