views:

1122

answers:

3

What is better adjacency lists or adjacency matrix for graph problems in c++? And what are the advantages and disadvantages of each?

EDIT:can anyone provide a link with a clean code for say Breadth first search in linked lists format ??

+4  A: 

It depends on the problem.

An adjacency matrix uses O(n*n) memory. It has fast lookups to check for presence or absence of a specific edge, but slow to iterate over all edges.

Adjacency lists use memory in proportion to the number edges, which might save a lot of memory if the adjacency matrix is sparse. It is fast to iterate over all edges, but finding the presence or absence specific edge is slightly slower than with the matrix.

Mark Byers
linked lists are harder to code , do you think they the implementation is worth spending some time learning it?
magiix
@magiix: Yes I think you should understand how to code linked lists if needed, but it's also important to not reinvent the wheel: http://www.cplusplus.com/reference/stl/list/
Mark Byers
can anyone provide a link with a clean code for say Breadth first search in linked lists format ??
magiix
@magiix: I think it's best to stick to one question per question, and not change it afterwards, otherwise things get very confusing. If you want to ask a new question, just create a new question.
Mark Byers
+1  A: 

It depends on what you're looking for.

With adjacency matrices you can answer fast to questions regarding if a specific edge between two vertices belongs to the graph, and you can also have quick insertions and deletions of edges. The downside is that you have to use excessive space, especially for graphs with many vertices, which is very efficient especially if your graph is sparse.

On the other hand, with adjacency lists it is harder to check whether a given edge is in a graph, because you have to search through the appropriate list to find the edge, but they are more space efficient.

Generally though, adjacency lists are the right data structure for most applications of graphs.

Alex
can anyone provide a link with a clean code for say Breadth first search in linked lists format ??
magiix
+1  A: 

If you are looking at graph analysis in C++ probably the first place to start would be the boost graph library, which implements a number of algorithms including BFS.

EDIT

This previous question on SO will probably help:

how-to-create-a-c-boost-undirected-graph-and-traverse-it-in-depth-first-search

Binary Nerd
Thanks you i ll check this library
magiix