What’s the best ways of implementing a graph in either C++ or Java? In C++, I was thinking about using a 2d array to do it. In java, I was considering an arrayList.
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
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:
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++):
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++):
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)
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.