简体   繁体   中英

Removing node from graph structure c#

I'm self-learning c# and I'm a little confused on nodes in graph structures. I've cobbled together this code so far, but I have no idea how to remove and entire node from the list:

public class Graph
{
    private int _V;
    private int _E;
    private LinkedList<Int32>[] adj;

    public Graph(int V)
    {
        this._V = V;
        adj = new LinkedList<Int32>[_V];
        for (int v = 0; v < _V; v++)
        {
            adj[v] = new LinkedList<Int32>();
        }
    }

    public void AddEdge(int v, int w)
    {
        _E++;
        adj[v].AddFirst(w);
        adj[w].AddFirst(v);
    }

    public void RemoveEdge(int v, int w)
    {
        _E--;
        adj[v].Remove(w);
        adj[w].Remove(v);
    }

    public IEnumerable<Int32> Adj(int v)
    {
        return adj[v];
    }

    public int V()
    {
        return _V;
    }

    public bool isLeaf(int v)
    {
        return adj[v].Count() == 1;
    }

    public int adjacencies(int v)
    {
        return adj[v].Count();
    }

    public String toString()
    {
        StringBuilder s = new StringBuilder();
        String NEWLINE = Environment.NewLine;
        s.Append(adj[1].Count + NEWLINE);
        s.Append(_V + " vertices, " + _E + " edges " + NEWLINE);
        for (int v = 0; v < _V; v++) {
            s.Append(String.Format("{0:d}: ", v));
            foreach (int w in adj[v]) {
                s.Append(String.Format("{0:d} ", w));
            }
            s.Append(NEWLINE);
        }
        return s.ToString();
    }

}

So, if I have four nodes where node 1 has an edge to 2, 2 has edges to both 3 and 4, and 3 and 4 share an edge with each other, I want to remove node 1 completely since it's a leaf. I can remove the edge easily enough, but that node still remains in my list (just without an edge). How do I get rid of 1 completely? I thought I should be able to just do a adj.Remove(1), but that throws an error.

I realize this is probably super easy, but the answers I've looked through in here seem to be describing something different or I'm simply not getting how this works.

Thanks!

Arrays do not support removal. If you really need to encode the concept of "does not exist" into adj , then you could set adj[v] to a value that represents "does not exist". For example,

adj[v] = null.

Alternatively, you could store adjacencies in a Dictionary<Int32> . Instead of

private LinkedList<Int32>[] adj;

you would have

private Dictionary<Int32, LinkedList<Int32>> adj;

and you could remove vertex v by

adj.Remove(v); // don't forget to remove the edges

In either case, you would probably want to update the other methods to handle such "removed" vertices.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM