如何查找数组中项目之间的连接或关系?

时间:2016-07-06 19:37:04

标签: arrays algorithm data-structures

考虑下面的图像,它是一个项目数组:

enter image description here

数组中的项目按名为id的属性(黑色圆圈中的数字)排序

属性id是唯一的。

每个项目都有两个额外的属性(在圆圈的括号内):fromto

每个项目都通过fromto属性连接相关到另一个项目。示例(不在上图中):

Using kind of python syntax:

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

将上述示例视为循环链接列表。

可能存在与其他项目无关的项目(例如id = 3-项目。)

输入是数组中任意项的id

该算法应检索以下任何结果:

  • 数组数组。
  • 一系列循环链接列表。

根据上图,预期输出的例子是:

1.-给定id = 7,预期结果为:

An array containing this single array (or its equivalent circular linked list).
That is, the items connected by the blue line.
If the items in the inner array are rotated by N, it's ok.

output = [
    [
        {id:7,  from:m, to:k},
        {id:8,  from:k, to:i},
        {id:10, from:i, to:b},
        {id:2,  from:b, to:e},
        {id:4,  from:e, to:h},
        {id:1,  from:h, to:l},
        {id:6,  from:l, to:m}
    ]
]

2.-给定id = 2,预期结果为:

An array containing two arrays (or their equivalent circular linked list).
That is, the two collections of items connected by the red and the blue line.
If the items in the inner arrays are rotated by N, it's ok.

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

所以,问题是:

解决此问题的可能算法和数据结构是什么?

3 个答案:

答案 0 :(得分:1)

以下是Javascript中的示例,该算法的说明位于评论中,您可以在Chrome控制台中对其进行测试:

它是随机的,所以你可以运行几个测试。 如果没有找到路径,则抛出错误。

[{"id":1,"origin":"h","destination":"p"},{"id":2,"origin":"s","destination":"e"},...

结果:

重要样本取随机数,这只是一次运行, 对于每次运行,找到不同的结果,但算法是相同的

数组中的250个项目

[
    {"id":221,"origin":"q","destination":"c"},
    {"id":26,"origin":"o","destination":"q"},
    {"id":28,"origin":"j","destination":"o"},
    {"id":31,"origin":"c","destination":"j"}
]

GitHub page

中填写json

找到路径的人:从“q”到“c”的id 221 完整的交易路线

classpath 'com.android.tools.build:gradle:2.0.0-alpha2'

答案 1 :(得分:0)

这是解决问题的递归算法的结构方法:

  • 从给定项目开始(例如7)
  • 搜索所有其他项目以获取连接(例如7,8)
  • 以这种方式建立一个链。存储所有采取的元素,以防止一个项目被采取两次。 (例如7,8,10,2)
  • 在某些时候将找不到更多元素(例如7,8,10,2,5,9)
  • 然后从链中删除最后一项,并搜索前一项是否有其他连接。 (例如7,8,10,2)
  • 减少并增加链直到您到达起始项目(例如7,8,10,2,4,1,6,7)

答案 2 :(得分:0)

我想要实现的是在有向图中找到通过给定顶点的所有循环。

修改Johnson算法是解决问题的正确方法。更多信息here