【问题标题】:How to order this graph?如何订购此图?
【发布时间】:2021-08-05 01:55:57
【问题描述】:

考虑到级别,我需要适当地排序图表。

假设我有这些数据:

const people = [
    {
        'name': 'john',
        'level': 0,
        'connections': ['monica', 'jeffrey']
    },
    {
        'name': 'monica',
        'level': 1,
        'connections': ['william']
    },
    {
        'name': 'jeffrey',
        'level': 1,
        'connections': ['george']
    },
    {
        'name': 'george',
        'level': 1,
        '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;
  });
});

我真的不喜欢在彼此之间有这么多循环。

问题是,我怎样才能使它更有效而不是复杂?

【问题讨论】:

  • 这是一种拓扑排序。维基百科文章有几个建议en.wikipedia.org/wiki/Topological_sorting
  • 你是正确的@ravenspoint。我正在寻找的是深度优先搜索。不过,我在多个父母链接到同一个孩子时遇到了一些困难。
  • 您发布的示例问题没有多个父母的孩子。无论如何,我不希望 Dijsktra 算法对多个父节点有任何问题 - 它只会为您提供从根节点到每个节点的最小深度。

标签: javascript algorithm graph computer-science graph-algorithm


【解决方案1】:

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++ 包装器。

【讨论】:

    猜你喜欢
    • 2021-08-11
    • 2017-08-23
    • 1970-01-01
    • 2018-04-05
    • 1970-01-01
    • 2021-03-23
    • 1970-01-01
    • 2021-06-06
    • 1970-01-01
    相关资源
    最近更新 更多