Exemplo n.º 1
0
        public int CountConnectedComponents()
        {
            int componentCount  = 0;
            int componentNumber = 1;
            Dictionary <T, int>            components = new Dictionary <T, int>();
            HashSet <UnorderedPair <int> > merged     = new HashSet <UnorderedPair <int> >();

            foreach (UnorderedPair <T> edge in _edges)
            {
                bool containsFirst  = components.ContainsKey(edge.First);
                bool containsSecond = components.ContainsKey(edge.Second);

                if (!containsFirst && !containsSecond)
                {
                    // New edge; create a new component.
                    components.Add(edge.First, componentNumber);
                    components.Add(edge.Second, componentNumber);
                    componentNumber++;
                    componentCount++;
                }
                else if (containsFirst && containsSecond)
                {
                    if (components[edge.First] != components[edge.Second])
                    {
                        UnorderedPair <int> record = new UnorderedPair <int>(components[edge.First], components[edge.Second]);

                        // Merge two components.
                        if (!merged.Contains(record))
                        {
                            merged.Add(record);
                            componentCount--;
                        }
                    }
                }
                else if (containsFirst)
                {
                    if (components.ContainsKey(edge.Second))
                    {
                        components[edge.Second] = components[edge.First];
                    }
                    else
                    {
                        components.Add(edge.Second, components[edge.First]);
                    }
                }
                else if (containsSecond)
                {
                    if (components.ContainsKey(edge.First))
                    {
                        components[edge.First] = components[edge.Second];
                    }
                    else
                    {
                        components.Add(edge.First, components[edge.Second]);
                    }
                }
            }

            return(componentCount + (_vertices.Count - components.Count));
        }
Exemplo n.º 2
0
 public bool DeleteEdge(UnorderedPair <T> edge)
 {
     return(_edges.Remove(edge));
 }
Exemplo n.º 3
0
 public bool AddEdge(UnorderedPair <T> edge)
 {
     return(_edges.Add(edge));
 }
Exemplo n.º 4
0
 public bool Equals(UnorderedPair <T> pair)
 {
     return(_first.Equals(pair._first) && _second.Equals(pair._second));
 }