问题描述
考虑到级别,我需要适当地对图表进行排序。
假设我有这些数据:
const people = [
{
'name': 'john','level': 0,'connections': ['monica','jeffrey']
},{
'name': 'monica','level': 1,'connections': ['william']
},{
'name': 'jeffrey','connections': ['george']
},{
'name': 'george','connections': []
},{
'name': 'william','level': 2,'connections': ['rachel']
},{
'name': 'rachel','level': 3,'connections': []
}
]
我怎样才能输出正确的顺序来形成它们?
正确顺序示例:
/*
[
John
- Monica
-- William
--- Rachel
- Jeffrey
-- George
]
*/
// (No need to worry about -)
我试过了:
let orderCounter = 1;
people.forEach(person => {
person['order'] = person['order'] || ++orderCounter;
if (person.connections > 0)
person.connections.forEach(connection => {
const foundPerson = people.find(x => x === connection);
foundPerson['order'] = foundPerson['order'] || ++orderCounter;
});
});
我真的不喜欢彼此之间有这么多循环。
问题是,我怎样才能使这更有效而不是令人费解?
解决方法
Dijsktra 算法在经过良好测试的库中广泛可用,并提供了一种直接的方法来解决此类问题(以及许多其他问题)
将您的示例数据转换为一个空格分隔的文本文件,所有链接的成本为 1,运行 Dijsktra 的 boost 图实现给出输出:
C:\Users\James\code\PathFinder\bin>gui
l john monica 1
l john jeffrey 1
l monica william 1
l jeffrey george 1
l william rachel 1
s john
e all
Hop count from root to every node:
john to monica 1
john to jeffrey 1
john to william 2
john to george 2
john to rachel 3
Boost graph implementation of Dijsktra
PathFinder 是 Dijsktra 的 Boost 图实现的 C++ 包装器。