我编写的以下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;
}
答案 0 :(得分:1)