这是检测无向图中循环的最佳算法吗?

时间:2017-05-14 17:57:28

标签: cycle dfs undirected-graph

我编写的以下C#算法在O(n)时间内检测到无向图中存在循环。它避免了递归并利用Dictionaries和HashSet的散列。但是我有办法做得更好吗?

void Main()
{
    var graph = new Dictionary<int, HashSet<int>>
    {
        { 0, new HashSet<int> { 4 } },
        { 1, new HashSet<int> { 2, 3, 4 } },
        { 2, new HashSet<int> { 1 } },
        { 3, new HashSet<int> { 1, 4 } },
        { 4, new HashSet<int> { 0, 1, 3 } }
    };

    Console.WriteLine(HasCycle(graph, 0));
}

bool HasCycle(Dictionary<int, HashSet<int>> graph, int start)
{
    var stack = new Stack<int>();
    var visited = new HashSet<int>();
    stack.Push(start);
    var curr = start;
    var prev = -1;
    while (stack.Count > 0)
    {
        prev = curr;
        curr = stack.Pop();
        visited.Add(curr);
        HashSet<int> neighbors;
        if (graph.TryGetValue(curr, out neighbors) && neighbors != null)
        {
            foreach (var neighbor in neighbors)
            {
                if (!visited.Contains(neighbor))
                {
                    stack.Push(neighbor);
                }
                else if (neighbor != prev && neighbors.Contains(prev))
                {
                    return true;
                }
            }
        }
    }
    return false;
}

1 个答案:

答案 0 :(得分:1)

DFS是确定图表中周期的最佳方法

Geeksforgeeks cycle detect from undirected graph

我会推荐你​​从这里学习并申请dfs。