微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如果任何组件在 C#

如何解决如果任何组件在 C#

我正在一个无向图上执行 DFS,目标是获取我稍后想要读出的所有簇。为此,我实例化了 edges 类型的 List<Tuple<int,int>>vertices一个简单的整数数组。 DFS(graph,vertex) 返回整数的 HashSet。问题是 while 循环中的最后一行,如何从 edges删除所有已经访问过的元素?

using System;
using System.Collections.Generic;
using System.Collections;
using System.Linq;

public class Test {
    static public void Main(String[] args)
    {
        var vertices = Enumerable.Range(0,10).ToArray();
        var edges = new List<Tuple<int,int>> {};
        edges.Add(Tuple.Create(1,4));
        edges.Add(Tuple.Create(4,1));
        edges.Add(Tuple.Create(3,5));
        edges.Add(Tuple.Create(5,3));

        var graph = new Graph<int>(vertices,edges);
        var algorithms = new GraphAlgorithms();
        var visited = new List<HashSet<int>>();

        // Apply DFS while there are clusters left
        while (edges.Any())
        {
            visited.Add(algorithms.DFS(graph,edges[0].Item1));
            edges.RemoveAll(node => visited.Contains(node));
        }
    }
}

如果您想自己尝试,这里是引用的类 GraphGraphAlgorithms

using System;
using System.Collections.Generic;

public class Graph<T> 
{
    public Graph() {}
    public Graph(IEnumerable<T> vertices,IEnumerable<Tuple<T,T>> edges)
    {
        foreach(var vertex in vertices)
            AddVertex(vertex);

        foreach(var edge in edges)
            AddEdge(edge);
    }

    public Dictionary<T,HashSet<T>> AdjacencyList { get; } = new Dictionary<T,HashSet<T>>();

    public void AddVertex(T vertex) 
    {
        AdjacencyList[vertex] = new HashSet<T>();
    }

    public void AddEdge(Tuple<T,T> edge) 
    {
        if (AdjacencyList.ContainsKey(edge.Item1) && AdjacencyList.ContainsKey(edge.Item2)) 
        {
            AdjacencyList[edge.Item1].Add(edge.Item2);
            AdjacencyList[edge.Item2].Add(edge.Item1);
        }
    }
}

using System.Collections.Generic; 

public class GraphAlgorithms {
    public HashSet<T> DFS<T>(Graph<T> graph,T start) {
        var visited = new HashSet<T>();

        if (!graph.AdjacencyList.ContainsKey(start))
            return visited;
            
        var stack = new Stack<T>();
        stack.Push(start);

        while (stack.Count > 0) {
            var vertex = stack.Pop();

            if (visited.Contains(vertex))
                continue;

            visited.Add(vertex);

            foreach(var neighbor in graph.AdjacencyList[vertex])
                if (!visited.Contains(neighbor))
                    stack.Push(neighbor);
        }

        return visited;
    }
}

非常感谢任何帮助:)

我正在重新发布我以前的问题的编辑版本,我现在删除了该问题,因为之前的问题缺少一个最小的可重现示例。

解决方法

从我看来,您的 visited 不应该是 List<Hashset<int>>,而应该只是 Hashset<int>,因此您的代码将更改为:

var visited = new HashSet<int>();
while(edges.Any())
{
    visited.UnionWith(algorithms.DFS(graph,edges[0].Item1));
    edges.RemoveAll(tuple => visited.Contains(tuple.Item1));
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。