[Solved] Implementing a graph in either C++ or Java [closed]


Firstly, language choices aren’t the most massive issue in the world, in my opinion. Unless you have a requirement to use a specific language or on portability, using either C++ or Java will be sufficient. Having said that, your question seems somewhat homework-ish. Are you using Prim’s algorithm for your MST implementation?

As other answers have already said, there are a few ways to represent graphs. The two that I’m most familiar with for representing graphs are:

  1. An Adjacency Matrix, which is a 2D array where each “row” and “column” is a node, and a value at that position of the matrix indicates an edge (or an edge weight) and a null-value (or a 0-value, or some other sentinel/meaningful value) indicates no edge
  2. An Adjacency List, which is a 2D array (kinda), where the i-th list is the list of all the nodes that are connected to (adjacent to) node i. At times, you may also choose to make the list a list of pairs of node names and edge weights, if your graph is directed/weighted.

In the adjacency list article on Wikipedia (linked above) there is a section on tradeoffs between the two representations.

On the subject of the MST algorithm:

You will probably get better performance using an adjacency list, out of the top of my head, but that’s only theoretically (I think?). Implementation-wise, there are things such as locality of reference to take into account. I would personally prefer, for ease of coding, however, to use an adjacency matrix (I just personally find them easier to work with, especially on weighted graphs), unless there’s a need for really good performance.

Adjacency Matrix (C++):

vector<vector<int> > adj_Mat(n, vector<int>(n, 0));

where n is the number of nodes in the graph. Then adj_Mat[i][j] is the weight of the edge between nodes i and j.

Adjacency List (C++):

vector<vector<pair<int, int> > > adj_list(n);

Then, if the i-th node has an edge weight of k to node j, I’d do something like this (assuming the graph is directed)

adj_list[i].push_back(pair<int, int>(j, k));

Now, my C++ is really hacky because I tend to use it for hacking random code in coding competitions, so this isn’t really good code but it’s really basic ways to code up these data representations.

Sorry about the massive rant, and I hope it does help.

2

solved Implementing a graph in either C++ or Java [closed]