如何按依赖性对依赖对象进行排序


76

我有一个收藏:

List<VPair<Item, List<Item>> dependencyHierarchy;

成对的第一个项目是某个对象(项目),第二个项目是第一个项目所依赖的相同类型对象的集合。我想获得一个List<Item>依序排列的依存关系,因此没有依赖于第一个元素的项目,依此类推(没有循环依存关系!)。

输入:

Item4取决于Item3和Item5
Item3取决于Item1
Item1不依赖任何一个
Item2取决于Item4 
Item5不依赖于任何一个 

结果:

项目1
项目5
项目3
项目4
项目2

谢谢。

解:

拓扑排序(感谢LoïcFévrier的想法)

例如在C#中例如Java的 (感谢xcud伟大的例子)


对于遇到此问题并寻找C#nuget包的任何人,这是我创建的一个包:github.com/madelson/MedallionTopologicSort
ChaseMedallion

Answers:



89

经过一段时间的努力,这是我尝试使用Linq风格的TSort扩展方法:

public static IEnumerable<T> TSort<T>( this IEnumerable<T> source, Func<T, IEnumerable<T>> dependencies, bool throwOnCycle = false )
{
    var sorted = new List<T>();
    var visited = new HashSet<T>();

    foreach( var item in source )
        Visit( item, visited, sorted, dependencies, throwOnCycle );

    return sorted;
}

private static void Visit<T>( T item, HashSet<T> visited, List<T> sorted, Func<T, IEnumerable<T>> dependencies, bool throwOnCycle )
{
    if( !visited.Contains( item ) )
    {
        visited.Add( item );

        foreach( var dep in dependencies( item ) )
            Visit( dep, visited, sorted, dependencies, throwOnCycle );

        sorted.Add( item );
    }
    else
    {
        if( throwOnCycle && !sorted.Contains( item ) )
            throw new Exception( "Cyclic dependency found" );
    }
}

5
+1简单得多,似乎对我有用。我所做的唯一的变化是使用Dictionary<T, object>,而不是List<T>用于visited-它应该是非常大的集合速度更快。
EM0 2012年

3
谢谢EM-我已更新为对访问的集合使用HashSet。
Mesmo 2012年

2
+1我在Wikipedia上查看了该算法的伪代码,并认为它很容易实现,但实际实现起来更容易!
ta.speot。是2012年

17
谢谢DMM!这对我来说只有一个修改:在末尾if( !visited.Contains( item ) ),我添加了类似的内容(在Java中)else if(!sorted.contains(item)){throw new Exception("Invalid dependency cycle!");}来管理A-> B,B-> C和C-> A的情况。
电子版

3
非常有用的答案,但是,想象一下场景sources = {A, B},在这里dependencies(B) = {A}。您所拥有的代码会将其检测为“循环依赖项”,这似乎是不正确的。
Supericy

20

有一个小问题

对于我们那些不想重新发明轮子的人:使用nuget安装QuickGraph .NET库,该库包括包括拓扑排序在内的多种图形算法。

要使用它,您需要创建AdjacencyGraph<,>诸如的实例AdjacencyGraph<String, SEdge<String>>。然后,如果您包括适当的扩展名:

using QuickGraph.Algorithms;

您可以致电:

var sorted = myGraph.TopologicalSort();

获取已排序节点的列表。


12

我喜欢DMM的答案,但是它假定输入节点是叶子(可能是预期的也可能不是)。

我将发布一个使用LINQ的替代解决方案,该解决方案没有做出此假设。此外,此解决方案yield return还能够快速返回叶子(例如使用TakeWhile)。

public static IEnumerable<T> TopologicalSort<T>(this IEnumerable<T> nodes, 
                                                Func<T, IEnumerable<T>> connected)
{
    var elems = nodes.ToDictionary(node => node, 
                                   node => new HashSet<T>(connected(node)));
    while (elems.Count > 0)
    {
        var elem = elems.FirstOrDefault(x => x.Value.Count == 0);
        if (elem.Key == null)
        {
            throw new ArgumentException("Cyclic connections are not allowed");
        }
        elems.Remove(elem.Key);
        foreach (var selem in elems)
        {
            selem.Value.Remove(elem.Key);
        }
        yield return elem.Key;
    }
}

这是到目前为止我所看到的最紧凑的拓扑排序实现。
Timo

1
“但它假设输入节点是叶子”,我不明白。你可以解释吗?
osexpert

1
@osexpert,这就是算法的工作方式:我们需要始终使用叶子-不依赖于任何其他节点的节点。此代码可确保:var elem = elems.FirstOrDefault(x => x.Value.Count == 0);。特别是,x.Value.Count == 0确保给定节点没有依赖性。
Danylo Yelizarov

而且,该实现是紧凑的,但是不是最佳的。我们在每次迭代中搜索一片叶子,使其为O(n ^ 2)。通过在while循环之前创建一个包含所有叶子的队列,然后将新项目添加到其中(只要它们变为“独立”),就可以改进此问题。
Danylo Yelizarov

是的,IIRC的确是基于我写的一些东西,该东西是我为处理编译器中的依赖性而编写的,该编译器具有成百上千个模块的顺序,如果执行得当的话。
Krumelur

6

这是我自己对拓扑排序的重新实现,该想法基于http://tawani.blogspot.com/2009/02/topological-sorting-and-cyclic.html(移植的Java源代码会占用太多内存,检查50k对象的费用为50k * 50k * 4 = 10GB,这是不可接受的。此外,在某些地方,它仍然具有Java编码约定)

using System.Collections.Generic;
using System.Diagnostics;

namespace Modules
{
    /// <summary>
    /// Provides fast-algorithm and low-memory usage to sort objects based on their dependencies. 
    /// </summary>
    /// <remarks>
    /// Definition: http://en.wikipedia.org/wiki/Topological_sorting
    /// Source code credited to: http://tawani.blogspot.com/2009/02/topological-sorting-and-cyclic.html    
    /// Original Java source code: http://www.java2s.com/Code/Java/Collections-Data-Structure/Topologicalsorting.htm
    /// </remarks>
    /// <author>ThangTran</author>
    /// <history>
    /// 2012.03.21 - ThangTran: rewritten based on <see cref="TopologicalSorter"/>.
    /// </history>
    public class DependencySorter<T>
    {
        //**************************************************
        //
        // Private members
        //
        //**************************************************

        #region Private members

        /// <summary>
        /// Gets the dependency matrix used by this instance.
        /// </summary>
        private readonly Dictionary<T, Dictionary<T, object>> _matrix = new Dictionary<T, Dictionary<T, object>>();

        #endregion


        //**************************************************
        //
        // Public methods
        //
        //**************************************************

        #region Public methods

        /// <summary>
        /// Adds a list of objects that will be sorted.
        /// </summary>
        public void AddObjects(params T[] objects)
        {
            // --- Begin parameters checking code -----------------------------
            Debug.Assert(objects != null);
            Debug.Assert(objects.Length > 0);
            // --- End parameters checking code -------------------------------

            // add to matrix
            foreach (T obj in objects)
            {
                // add to dictionary
                _matrix.Add(obj, new Dictionary<T, object>());
            }
        }

        /// <summary>
        /// Sets dependencies of given object.
        /// This means <paramref name="obj"/> depends on these <paramref name="dependsOnObjects"/> to run.
        /// Please make sure objects given in the <paramref name="obj"/> and <paramref name="dependsOnObjects"/> are added first.
        /// </summary>
        public void SetDependencies(T obj, params T[] dependsOnObjects)
        {
            // --- Begin parameters checking code -----------------------------
            Debug.Assert(dependsOnObjects != null);
            // --- End parameters checking code -------------------------------

            // set dependencies
            Dictionary<T, object> dependencies = _matrix[obj];
            dependencies.Clear();

            // for each depended objects, add to dependencies
            foreach (T dependsOnObject in dependsOnObjects)
            {
                dependencies.Add(dependsOnObject, null);
            }
        }

        /// <summary>
        /// Sorts objects based on this dependencies.
        /// Note: because of the nature of algorithm and memory usage efficiency, this method can be used only one time.
        /// </summary>
        public T[] Sort()
        {
            // prepare result
            List<T> result = new List<T>(_matrix.Count);

            // while there are still object to get
            while (_matrix.Count > 0)
            {
                // get an independent object
                T independentObject;
                if (!this.GetIndependentObject(out independentObject))
                {
                    // circular dependency found
                    throw new CircularReferenceException();
                }

                // add to result
                result.Add(independentObject);

                // delete processed object
                this.DeleteObject(independentObject);
            }

            // return result
            return result.ToArray();
        }

        #endregion


        //**************************************************
        //
        // Private methods
        //
        //**************************************************

        #region Private methods

        /// <summary>
        /// Returns independent object or returns NULL if no independent object is found.
        /// </summary>
        private bool GetIndependentObject(out T result)
        {
            // for each object
            foreach (KeyValuePair<T, Dictionary<T, object>> pair in _matrix)
            {
                // if the object contains any dependency
                if (pair.Value.Count > 0)
                {
                    // has dependency, skip it
                    continue;
                }

                // found
                result = pair.Key;
                return true;
            }

            // not found
            result = default(T);
            return false;
        }

        /// <summary>
        /// Deletes given object from the matrix.
        /// </summary>
        private void DeleteObject(T obj)
        {
            // delete object from matrix
            _matrix.Remove(obj);

            // for each object, remove the dependency reference
            foreach (KeyValuePair<T, Dictionary<T, object>> pair in _matrix)
            {
                // if current object depends on deleting object
                pair.Value.Remove(obj);
            }
        }


        #endregion
    }

    /// <summary>
    /// Represents a circular reference exception when sorting dependency objects.
    /// </summary>
    public class CircularReferenceException : Exception
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="CircularReferenceException"/> class.
        /// </summary>
        public CircularReferenceException()
            : base("Circular reference found.")
        {            
        }
    }
}

1

通过将Item的依赖项存储在Item本身中,我可以使自己更轻松:

public class Item
{
    private List<Item> m_Dependencies = new List<Item>();

    protected AddDependency(Item _item) { m_Dependencies.Add(_item); }

    public Item()
    {
    }; // eo ctor

    public List<Item> Dependencies {get{return(m_Dependencies);};}
} // eo class Item

然后,在此基础上,您可以实现一个自定义的List排序委托,该委托基于给定Item是否包含在其他依赖项列表中进行排序:

int CompareItem(Item _1, Item _2)
{
    if(_2.Dependencies.Contains(_1))
        return(-1);
    else if(_1.Dependencies.Contains(_2))
        return(1);
    else
        return(0);
}

3
订单不完整,因此无法使用。您需要为每个项目提供他或他的任何后代所依赖的所有项目的列表。(即,建立完整的有向无环图)容易找到一个反例:1取决于3和2,3等于4。[3 4 1 2]根据您的算法排序。但是3必须在1之后。
LoïcFévrier2010年

啊,谢谢。我没想到。非常感激。下选派来了!:)
Moo-Juice 2010年

Loic,您是否愿意进一步解释我的建议为何无效?并不是说这是对的,而是为了我可以更好地学习。我只是在这里尝试过,对于OP的示例和您的示例,我得到的列表都是按顺序排列的。靠运气吧?:)以您的示例(1取决于3和2,2取决于4),我得到的排序是[
4,3,2,1

1
为了排序列表,每个排序算法将仅检查是否对任何连续元素进行了排序。就您而言,排序方式是:第二个不依赖于第一个。[3 4 1 2]和[4、3、2、1]是两个可能的顺序。该算法假定传递性:如果x <= y并且y <= z,则x <= z。在这种情况下,这是不正确的。但是,您可以修改数据:如果x取决于y,y取决于z,则将z添加到x'依赖项列表中。现在,您的部分订单是完整的部分订单,并且可以使用排序算法。但是“完成它”的复杂度为O(N ^ 2),其中拓扑排序也是如此。
卢瓦克FEVRIER

感谢您抽出宝贵的时间对此做进一步解释。在进一步的测试中,我的想法确实的确破灭了。编程愉快!
Moo-Juice 2010年

1

对于只有一个“父母”的情况,有不同的想法:

您可以代替父母来存放父母。
因此,您可以轻松地判断问题是否是其他问题的依存关系。
然后使用Comparable<T>,它将声明依赖性“较小”和依赖性“更大”。
然后简单地打电话Collections.sort( List<T>, ParentComparator<T>);

对于多父级方案,将需要树搜索,这将导致执行缓慢。但这可以通过A *排序矩阵形式的缓存来解决。


1

我将DMM的想法与Wikipedia上的深度优先搜索算法合并。它可以完美满足我的需求。

public static class TopologicalSorter
{
public static List<string> LastCyclicOrder = new List<string>(); //used to see what caused the cycle

sealed class ItemTag
{
  public enum SortTag
  {
    NotMarked,
    TempMarked,
    Marked
  }

  public string Item { get; set; }
  public SortTag Tag { get; set; }

  public ItemTag(string item)
  {
    Item = item;
    Tag = SortTag.NotMarked;
  }
}

public static IEnumerable<string> TSort(this IEnumerable<string> source, Func<string, IEnumerable<string>> dependencies)
{
  TopologicalSorter.LastCyclicOrder.Clear();

  List<ItemTag> allNodes = new List<ItemTag>();
  HashSet<string> sorted = new HashSet<string>(StringComparer.OrdinalIgnoreCase);

  foreach (string item in source)
  {
    if (!allNodes.Where(n => string.Equals(n.Item, item, StringComparison.OrdinalIgnoreCase)).Any())
    {
      allNodes.Add(new ItemTag(item)); //don't insert duplicates
    }
    foreach (string dep in dependencies(item))
    {
      if (allNodes.Where(n => string.Equals(n.Item, dep, StringComparison.OrdinalIgnoreCase)).Any()) continue; //don't insert duplicates
      allNodes.Add(new ItemTag(dep));
    }
  }

  foreach (ItemTag tag in allNodes)
  {
    Visit(tag, allNodes, dependencies, sorted);
  }

  return sorted;
}

static void Visit(ItemTag tag, List<ItemTag> allNodes, Func<string, IEnumerable<string>> dependencies, HashSet<string> sorted)
{
  if (tag.Tag == ItemTag.SortTag.TempMarked)
  {
    throw new GraphIsCyclicException();
  }
  else if (tag.Tag == ItemTag.SortTag.NotMarked)
  {
    tag.Tag = ItemTag.SortTag.TempMarked;
    LastCyclicOrder.Add(tag.Item);

    foreach (ItemTag dep in dependencies(tag.Item).Select(s => allNodes.Where(t => string.Equals(s, t.Item, StringComparison.OrdinalIgnoreCase)).First())) //get item tag which falls with used string
      Visit(dep, allNodes, dependencies, sorted);

    LastCyclicOrder.Remove(tag.Item);
    tag.Tag = ItemTag.SortTag.Marked;
    sorted.Add(tag.Item);
  }
}
}

1

我不喜欢递归方法,所以DMM不可用。Krumelur看起来不错,但似乎占用了大量内存?提出了一种似乎可行的基于堆栈的替代方法。使用与DMM相同的DFS逻辑,并且在测试时我将此解决方案用作比较。

    public static IEnumerable<T> TopogicalSequenceDFS<T>(this IEnumerable<T> source, Func<T, IEnumerable<T>> deps)
    {
        HashSet<T> yielded = new HashSet<T>();
        HashSet<T> visited = new HashSet<T>();
        Stack<Tuple<T, IEnumerator<T>>> stack = new Stack<Tuple<T, IEnumerator<T>>>();

        foreach (T t in source)
        {
            stack.Clear();
            if (visited.Add(t))
                stack.Push(new Tuple<T, IEnumerator<T>>(t, deps(t).GetEnumerator()));

            while (stack.Count > 0)
            {
                var p = stack.Peek();
                bool depPushed = false;
                while (p.Item2.MoveNext())
                {
                    var curr = p.Item2.Current;
                    if (visited.Add(curr))
                    {
                        stack.Push(new Tuple<T, IEnumerator<T>>(curr, deps(curr).GetEnumerator()));
                        depPushed = true;
                        break;
                    }
                    else if (!yielded.Contains(curr))
                        throw new Exception("cycle");
                }

                if (!depPushed)
                {
                    p = stack.Pop();
                    if (!yielded.Add(p.Item1))
                        throw new Exception("bug");
                    yield return p.Item1;
                }
            }
        }
    }

这也是基于堆栈的BFS变体。它将产生与上述结果不同的结果,但仍然有效。我不确定使用上面的DFS变体是否有任何优势,但是创建它很有趣。

    public static IEnumerable<T> TopologicalSequenceBFS<T>(this IEnumerable<T> source, Func<T, IEnumerable<T>> dependencies)
    {
        var yielded = new HashSet<T>();
        var visited = new HashSet<T>();
        var stack = new Stack<Tuple<T, bool>>(source.Select(s => new Tuple<T, bool>(s, false))); // bool signals Add to sorted

        while (stack.Count > 0)
        {
            var item = stack.Pop();
            if (!item.Item2)
            {
                if (visited.Add(item.Item1))
                {
                    stack.Push(new Tuple<T, bool>(item.Item1, true)); // To be added after processing the dependencies
                    foreach (var dep in dependencies(item.Item1))
                        stack.Push(new Tuple<T, bool>(dep, false));
                }
                else if (!yielded.Contains(item.Item1))
                    throw new Exception("cyclic");
            }
            else
            {
                if (!yielded.Add(item.Item1))
                    throw new Exception("bug");
                yield return item.Item1;
            }
        }
    }

对于.NET 4.7+,我建议用ValueTuple替换Tuple,以减少内存使用量。在较早的.NET版本中,可以用KeyValuePair替换Tuple。


0

这是来自https://stackoverflow.com/a/9991916/4805491的重构代码。

// Version 1
public static class TopologicalSorter<T> where T : class {

    public struct Item {
        public readonly T Object;
        public readonly T Dependency;
        public Item(T @object, T dependency) {
            Object = @object;
            Dependency = dependency;
        }
    }


    public static T[] Sort(T[] objects, Func<T, T, bool> isDependency) {
        return Sort( objects.ToList(), isDependency ).ToArray();
    }

    public static T[] Sort(T[] objects, Item[] dependencies) {
        return Sort( objects.ToList(), dependencies.ToList() ).ToArray();
    }


    private static List<T> Sort(List<T> objects, Func<T, T, bool> isDependency) {
        return Sort( objects, GetDependencies( objects, isDependency ) );
    }

    private static List<T> Sort(List<T> objects, List<Item> dependencies) {
        var result = new List<T>( objects.Count );

        while (objects.Any()) {
            var obj = GetIndependentObject( objects, dependencies );
            RemoveObject( obj, objects, dependencies );
            result.Add( obj );
        }

        return result;
    }

    private static List<Item> GetDependencies(List<T> objects, Func<T, T, bool> isDependency) {
        var dependencies = new List<Item>();

        for (var i = 0; i < objects.Count; i++) {
            var obj1 = objects[i];
            for (var j = i + 1; j < objects.Count; j++) {
                var obj2 = objects[j];
                if (isDependency( obj1, obj2 )) dependencies.Add( new Item( obj1, obj2 ) ); // obj2 is dependency of obj1
                if (isDependency( obj2, obj1 )) dependencies.Add( new Item( obj2, obj1 ) ); // obj1 is dependency of obj2
            }
        }

        return dependencies;
    }


    private static T GetIndependentObject(List<T> objects, List<Item> dependencies) {
        foreach (var item in objects) {
            if (!GetDependencies( item, dependencies ).Any()) return item;
        }
        throw new Exception( "Circular reference found" );
    }

    private static IEnumerable<Item> GetDependencies(T obj, List<Item> dependencies) {
        return dependencies.Where( i => i.Object == obj );
    }

    private static void RemoveObject(T obj, List<T> objects, List<Item> dependencies) {
        objects.Remove( obj );
        dependencies.RemoveAll( i => i.Object == obj || i.Dependency == obj );
    }

}


// Version 2
public class TopologicalSorter {

    public static T[] Sort<T>(T[] source, Func<T, T, bool> isDependency) {
        var list = new LinkedList<T>( source );
        var result = new List<T>();

        while (list.Any()) {
            var obj = GetIndependentObject( list, isDependency );
            list.Remove( obj );
            result.Add( obj );
        }

        return result.ToArray();
    }

    private static T GetIndependentObject<T>(IEnumerable<T> list, Func<T, T, bool> isDependency) {
        return list.First( i => !GetDependencies( i, list, isDependency ).Any() );
    }

    private static IEnumerable<T> GetDependencies<T>(T obj, IEnumerable<T> list, Func<T, T, bool> isDependency) {
        return list.Where( i => isDependency( obj, i ) ); // i is dependency of obj
    }

}
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.