Three ways to store a graph in memory, advantages and disadvantages

后端 未结 7 1722
别跟我提以往
别跟我提以往 2020-12-04 07:09

There are three ways to store a graph in memory:

  1. Nodes as objects and edges as pointers
  2. A matrix containing all edge weights between numbered node x a
相关标签:
7条回答
  • 2020-12-04 07:50

    There is another option: nodes as objects, edges as objects too, each edge being at the same time in two doubly-linked lists: the list of all edges coming out from the same node and the list of all edges going into the same node.

    struct Node {
        ... node payload ...
        Edge *first_in;    // All incoming edges
        Edge *first_out;   // All outgoing edges
    };
    
    struct Edge {
        ... edge payload ...
        Node *from, *to;
        Edge *prev_in_from, *next_in_from; // dlist of same "from"
        Edge *prev_in_to, *next_in_to;     // dlist of same "to"
    };
    

    The memory overhead is big (2 pointers per node and 6 pointers per edge) but you get

    • O(1) node insertion
    • O(1) edge insertion (given pointers to "from" and "to" nodes)
    • O(1) edge deletion (given the pointer)
    • O(deg(n)) node deletion (given the pointer)
    • O(deg(n)) finding neighbors of a node

    The structure also can represent a rather general graph: oriented multigraph with loops (i.e. you can have multiple distinct edges between the same two nodes including multiple distinct loops - edges going from x to x).

    A more detailed explanation of this approach is available here.

    0 讨论(0)
提交回复
热议问题