图的拓扑序列(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;
}
相关推荐
G***669141 分钟前
算法设计模式:贪心与动态规划
算法·设计模式·动态规划
墨染点香1 小时前
LeetCode 刷题【160. 相交链表】
算法·leetcode·链表
少睡点觉1 小时前
LeetCode 238. 除自身以外数组的乘积 问题分析+解析
java·算法·leetcode
大千AI助手1 小时前
多叉树:核心概念、算法实现与全领域应用
人工智能·算法·决策树·机器学习··多叉树·大千ai助手
一只老丸1 小时前
HOT100题打卡第38天——贪心算法
算法·贪心算法
普通网友1 小时前
高性能TCP服务器设计
开发语言·c++·算法
醒过来摸鱼1 小时前
9.12 sinc插值
python·线性代数·算法·numpy
普通网友1 小时前
C++与硬件交互编程
开发语言·c++·算法
liliangcsdn1 小时前
EnsembleRetriever中的倒数融合排序算法
算法·排序算法
HUTAC1 小时前
重要排序算法(更新ing)
数据结构·算法