如何从一系列项目创建有向图?

时间:2016-07-07 07:06:17

标签: arrays algorithm graph graph-theory

我有一组对象。

input = [
    {id:1,  from:h, to:l},
    {id:2,  from:b, to:e},
    {id:3,  from:p, to:q},
    {id:4,  from:e, to:h},
    {id:5,  from:e, to:g},
    {id:6,  from:l, to:m},
    {id:7,  from:m, to:k},
    {id:8,  from:k, to:i},
    {id:9,  from:g, to:i},
    {id:10, from:i, to:b}
]

数组中的项目按名为id的属性进行排序。

属性id是唯一的。

图表中的节点应通过fromto连接 数组中每个项目的属性。

示例(不基于上述数组):

{id:1, from:a, to:b} --> {id:2, from:b,to:c} --> {id:3, from:c, to:a}

算法的输出应为:

output = [
    {id:1,  from:h, to:l, next: [object with id = 6]},
    {id:2,  from:b, to:e, next: [object with id = 4, object with id = 5]},
    {id:3,  from:p, to:q, next: [null]},
    {id:4,  from:e, to:h, next: [object with id = 1]},
    {id:5,  from:e, to:g, next: [object with id = 9]},
    {id:6,  from:l, to:m, next: [object with id = 7]},
    {id:7,  from:m, to:k, next: [object with id = 8]},
    {id:8,  from:k, to:i, next: [object with id = 10]},
    {id:9,  from:g, to:i, next: [object with id = 10]},
    {id:10, from:i, to:b, next: [object with id = 2]}
]

因此,最终有向图应该如下所示:

this question

1 个答案:

答案 0 :(得分:1)

原始数据结构是边缘列表,是表示图形数据结构的一种相当标准的方法。我认为你将边缘与节点混淆。在列表中,id唯一标识边,小写字母唯一标识节点。

Graphviz是图形的一种很好的符号语言。转换为graphviz,您的图表可以这样写:

digraph G {
h -> l
b -> e
p -> q
e -> h
e -> g
l -> m
m -> k
k -> i
g -> i
i -> b
}

您可以使用http://www.webgraphviz.com/之类的在线工具以图形方式呈现此图片。这将得到如下结果。如您所见,这与您绘制的图表完全不同。

enter image description here