可以将对象列表分类为多个彼此对齐的互连对象组吗?
型号:
public class Item
{
public string Name {get;set;}
public List<Item> ConnectedItem {get;set;}
}
数据:
public void Data()
{
Item One = new Item() {};
Item Two = new Item() { };
Item Three = new Item() { };
Item Four = new Item() { };
Item Five = new Item() { };
Item Six = new Item() { };
Item Seven = new Item() { };
Item Eight = new Item() { };
Item Nine = new Item() { };
Item Ten = new Item() { };
One.ConnectedItem = new List<Item>(){Two,Three, Five};
Two.ConnectedItem = new List<Item>() { One, Five };
Three.ConnectedItem = new List<Item>() { Five, Two };
Four.ConnectedItem = new List<Item>() { One, Two };
Five.ConnectedItem = new List<Item>() { Four, One, Two ,Three };
Six.ConnectedItem = new List<Item>() { Eight };
Seven.ConnectedItem = new List<Item>() { Eight };
Eight.ConnectedItem = new List<Item>() { Six };
Nine.ConnectedItem = new List<Item>() { Ten };
Ten.ConnectedItem = new List<Item>() { Nine};
List<Item> items = new List<Item>(new List<Item>() {One,Two,Three,Four,Five,Six,Seven,Eight,Nine,Ten });
}
我想要存档的是互连项目列表的列表
-Collection1
----一,二,三,四,五个
-Collection2
----六,七,八个
-Collection3
----九个,十个
List<List<Item>> sortedList = new List<List<Item>>()
{
new List<Item>() {One, Two,Three,Four,Five},
new List<Item>() {Six,Seven,Eight},
new List<Item>() {Nine,Ten},
};
答案 0 :(得分:1)
您尝试做的是找到模型所暗示的图表的连接组件。通过从一个节点执行DFS可以找到连接的组件,在DFS完成后,您将继续查找尚未找到的节点。我假设您拥有数组或列表L
中的所有项目;我还将一个Visited属性添加到Item。
现在你有了一个有向图(Item1可能指向Item2,而Item2没有指向Item1)。显然,您正在寻找的是通过删除链接上的路线获得的图表的连通组件。
List<List<Item>> components = new List<List<Item>>();
for (int i = 0; i < L.Count; i++)
{
if (L.Visited)
continue;
var component = new List<Item>();
DFS(L[i], component);
components.Add(component);
}
和方法DFS:
static void DFS(Item item, List<Item> component)
{
if (component.Contains(item))
return;
component.Add(item);
item.Visited = true;
foreach (var i in item.ConnectedItems)
{
if (!i.Visited)
DFS(i, component);
}
foreach (var i in L)
{
if (!i.Visited && i.ConnectedItems.Contains(item))
DFS(i);
}
}