简体   繁体   中英

How can I represent edges for a graph in terms of a list?

我们如何将图表表示为边缘列表?

There's three common ways of doing this:

  1. Adjacency matrix: AV * V table of edge weights, where the ith column on the jth row is the weight of the edge between vertices i and j. If there is no edge, infinity is often used (or you can use some sentinel value, like -1).

  2. Adjacency lists: An array of V linked lists. Each ith list in the array is a list of edges leaving the ith vertice.

  3. Edge list: Simply a list of tuples (u, v) of edges.

Different ones are suitable for different purposes. Personally I find the adjacency lists to be the most useful, but if you have a very dense graph then an adjacency matrix can improvement performance and memory usage.

If you wanna store exactly edges, use matrix of weights: int** M; , where M[i][t] is the length of the edge between i and t vertices.

If your graph edges have weight of 1, you could store graph in adjacency matrix, where M[i][t] equals to:

  • 0 if there is no edges between i and t vertices
  • 1 if there is edge from i to t
  • alpha if i == t and there is a loop in i (or t) vertex

If you requre structure, critical for memory usage, store your graph in the linked list, where each vertex has structure:

struct Vertex
{
  int N;
  Vertex* next;
};

So you would have array of Vertex structures, each containing pointer to the next it is connected to. For example, here is some linked-list-graph:

  • 1 -> 3 -> 4
  • 2 -> 5
  • 3 -> 4
  • 4 -> 3
  • 5 -> 2

Unless you really want to implement the representation yourself, as a learning exercise or to have more control, consider using a library such as igraph which is a C library for representing and manipulating graphs. Or go one abstraction level down - build adjacency lists or edge lists yourself, but use the list-building capabilities of glib rather than rolling your own.

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