算法笔记 DFS闭环检测
按深度优先检测是否存在闭环,该方法通过 DFS 遍历图,使用 visited 集合记录所有已访问节点(防止重复遍历),使用 stack 集合记录当前路径上的节点。
当 DFS 遇到一个已经在当前路径 (stack) 上的节点时,就判定存在环。外层循环确保遍历所有可能的起始节点.
private bool HasCycle(List<(Guid from, Guid to)> edges)
{
var dict = new Dictionary<Guid, List<Guid>>();
foreach (var (from, to) in edges)
{
if (!dict.ContainsKey(from))
dict[from] = new List<Guid>();
dict[from].Add(to);
}
var visited = new HashSet<Guid>();
var stack = new HashSet<Guid>();
bool Dfs(Guid node)
{
if (stack.Contains(node)) return true;
if (visited.Contains(node)) return false;
visited.Add(node);
stack.Add(node);
if (dict.ContainsKey(node))
{
foreach (var next in dict[node])
{
if (Dfs(next)) return true;
}
}
stack.Remove(node);
return false;
}
foreach (var node in dict.Keys)
{
if (Dfs(node)) return true;
}
return false;
}

浙公网安备 33010602011771号