图的拓扑序列(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;
}
相关推荐
老马啸西风3 分钟前
力扣 LC27. 移除元素 remove-element
算法·面试·github
数智顾问7 分钟前
中秋特别篇:使用QtOpenGL和着色器绘制星空与满月——从基础框架到光影渲染
算法
txwtech10 分钟前
第5篇 如何计算两个坐标点距离--opencv图像中的两个点
人工智能·算法·机器学习
CoovallyAIHub11 分钟前
YOLO26学界首评:四大革新点究竟有多强?
深度学习·算法·计算机视觉
用户9163574409511 分钟前
LeetCode热题100——11.盛最多水的容器
javascript·算法
Gorgous—l24 分钟前
数据结构算法学习:LeetCode热题100-矩阵篇(矩阵置零、螺旋矩阵、旋转图像、搜索二维矩阵 II)
数据结构·学习·算法
2401_8414956444 分钟前
【计算机视觉】霍夫变换函数的参数调整
人工智能·python·算法·计算机视觉·霍夫变换·直线检测·调整策略
练习前端两年半44 分钟前
🔍 你真的会二分查找吗?
前端·javascript·算法
搂鱼1145142 小时前
GJOI 10.7/10.8 题解
算法
Django强哥2 小时前
JSON Schema Draft-07 详细解析
javascript·算法·代码规范