aboutsummaryrefslogtreecommitdiffstats
path: root/utils/Collections/GraphExtensions.cs
blob: 0a9c74ff78141f59a2253c6f7f891c14850c3827 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
/***************************************************************************************************
 Copyright (C) 2025 The Qt Company Ltd.
 SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
***************************************************************************************************/

using System.Collections;

namespace Qt.DotNet.Utils.Collections
{
    public static class GraphExtensions
    {
        public static IEnumerable<T> FindCycle<T, LT>(this IDictionary<T, LT> graph)
            where LT : IEnumerable<T>
        {
            HashSet<T> visited = new();
            HashSet<T> inPath = new();
            Stack<T> stack = new();
            foreach (var node in graph.Keys) {
                if (visited.Contains(node))
                    continue;
                stack.Push(node);
                while (stack.Any()) {
                    var top = stack.Peek();
                    if (!visited.Contains(top)) {
                        visited.Add(top);
                        inPath.Add(top);
                    } else {
                        inPath.Remove(top);
                        stack.Pop();
                    }
                    if (!graph.ContainsKey(top))
                        continue;
                    foreach (var adj in graph[top]) {
                        if (!visited.Contains(adj))
                            stack.Push(adj);
                        else if (inPath.Contains(adj))
                            return stack.Prepend(adj);
                    }
                }
            }
            return null;
        }

        public static bool IsCyclic<T, LT>(this IDictionary<T, LT> graph)
            where LT : IEnumerable<T>
        {
            return graph.FindCycle()?.Any() ?? false;
        }
    }
}