Reputation: 39
How can we represent a graph as a list of edges?
Upvotes: 3
Views: 4899
Reputation: 11963
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.
Upvotes: 0
Reputation: 12225
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:
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:
Upvotes: 1
Reputation: 54270
There's three common ways of doing this:
Adjacency matrix: A V * 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).
Adjacency lists: An array of V linked lists. Each ith list in the array is a list of edges leaving the ith vertice.
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.
Upvotes: 6