【发布时间】:2018-03-11 02:48:25
【问题描述】:
鉴于以下重定向列表
[
{
"old": "a",
"target": "b"
},
{
"old": "b",
"target": "c"
},
{
"old": "c",
"target": "d"
},
{
"old": "d",
"target": "a"
},
{
"old": "o",
"target": "n"
},
{
"old": "n",
"target": "b"
},
{
"old": "j",
"target": "x"
},
{
"old": "whatever",
"target": "something"
}
]
在这里我们可以看到第一项“a”应该重定向到“b”。 如果我们遵循列表,我们可以看到以下模式:
a -> b
b -> c
c -> d
d -> a
所以我们最终会得到一个循环引用,因为“a”最终会指向“d”而“d”指向“a”。
找到循环引用的最有效方法是什么?
我在 C# 中提出了以下算法
var items = JsonConvert.DeserializeObject<IEnumerable<Item>>(json)
.GroupBy(x => x.Old)
.Select(x => x.First())
.ToDictionary(x => x.Old, x => x.Target);
var circulars = new Dictionary<string, string>();
foreach (var item in items)
{
var target = item.Value;
while (items.ContainsKey(target))
{
target = items[target];
if (target.Equals(item.Key))
{
circulars.Add(target, item.Value);
break;
}
}
}
这会给我一个包含 4 个项目的列表,如下所示:
[
{
"old": "a",
"target": "b"
},
{
"old": "b",
"target": "c"
},
{
"old": "c",
"target": "d"
},
{
"old": "d",
"target": "a"
}
]
但我只对告诉用户类似的事情感兴趣
“嘿,你不能那样做,这将是一个循环引用,因为“a”指向“b”,“b”指向“c”,“d”指向“a”
那么,你们有什么建议吗? 我确信存在一些其他(更好的)算法可以做到这一点...... :)
【问题讨论】:
-
尝试图论中的循环检测算法。
-
马上查一下,谢谢! :)
-
还是“嘿,你不能那样做,B 和 C 是循环引用,因为 A 和 D”? - 你只能报告一个循环 - 它没有开始和结束 - 这是一个循环。
-
嗯,好问题。目标是通知用户,由于 B、C 和 D,他们最终会进入重定向循环(我猜?)
-
在我们的软件中,我们说“检测到循环,包括节点:A、B、C、D”。
标签: c# algorithm circular-reference cycle-detection