0

I'm trying to implement a graph in C++, I'm not sure if there is a 'proper' way of going about this. should each of my vertices contain a list of vertices it points to, or should the graph object contain a list of vertices and a list of edges.

kjh
  • 3,407
  • 8
  • 42
  • 79
  • There is no single best representation. What's your use case? –  Oct 04 '13 at 15:52
  • This may be very vague, but I just want to store some simple integers at each vertex so that I can try to implement Dijkstra's algorithm. – kjh Oct 04 '13 at 16:07
  • Then look at the pseudocode for Dijkstra's algorithm and decide which representation is more convenient for that application. –  Oct 04 '13 at 16:19
  • Doesn't Dijsktra work over evaluated edges instead of vertices? Or are you trying some variation of it? – Erbureth Oct 04 '13 at 16:22

2 Answers2

1

This depends on what type of graph you are dealing with, If your graph is weighted, you can't just have a list of pointers because you won't be able to assign a weight for this connection. In this case I would suggest that every node will contain a list of edges that are connected to it. if the graph is not directed, then for any vertices i and j you can save a pointer to the same edge {i, j}, if it is directed then edge {i, j} and {j, i} are two different object.

Another approach is to save an NxN matrix that represents the connections between all the vertices. if the graph is not weighted, then each cell [i, j] will have 1 if a edge exists between vertex i to vertex j. if the graph is weighted then cell [i, j] will contain the distance between vertex i to vertex j, and infinity or -1 if the edges doesn't exist.

If your graph is complete (every vertex is connected to all the other vertices), I strongly recommend using the matrix technique, as it is very easy to implement, gives you direct access to any relevant value, and doesn't take extra memory or running time (for example, when you want to iterate through all the edges connected to a certain vertex), as any vertex will contain a list of connections to all the other vertices anyway.

Ron Teller
  • 1,880
  • 1
  • 12
  • 23
0

It depends on your access the graph data. You can define two dimentional vector as follows:

vector< vector<int> > nodes;

where nodes ids are 0 to number_of_nodes -1; node 6 would be stored in nodes[6], and son on.

JB.
  • 40,344
  • 12
  • 79
  • 106
Ali
  • 1