考虑下面的图像,它是一个项目数组:
数组中的项目按名为id
的属性(黑色圆圈中的数字)排序
属性id
是唯一的。
每个项目都有两个额外的属性(在圆圈的括号内):from
和to
每个项目都通过from
和to
属性连接或相关到另一个项目。示例(不在上图中):
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}
]
]
所以,问题是:
解决此问题的可能算法和数据结构是什么?
答案 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"}
]
中填写json
找到路径的人:从“q”到“c”的id 221 完整的交易路线
classpath 'com.android.tools.build:gradle:2.0.0-alpha2'
答案 1 :(得分:0)
这是解决问题的递归算法的结构方法:
答案 2 :(得分:0)
我想要实现的是在有向图中找到通过给定顶点的所有循环。
修改Johnson算法是解决问题的正确方法。更多信息here。