Computernerd
Computernerd

Reputation: 7782

Questions regarding Implementation of graph in c++

I am learning to implement a graph in C++ hence i read Wikipedia entry and found out there are two commonly used methods : Adjacency list and Adjacency matrix. I understand the tradeoff in space between Adjacency list and Adjacency matrix.

I have three questions

1) Are there any more ways other than the two listed above to implement the graph ??

2) What are the differences between using the different data structures ??? Linked List VS Vector VS Map

3) What does the following paragraph mean in the article

The other significant difference between adjacency lists and adjacency matrices is in the efficiency of the operations they perform. In an adjacency list, the neighbors of each vertex may be listed efficiently, in time proportional to the degree of the vertex. In an adjacency matrix, this operation takes time proportional to the number of vertices in the graph, which may be significantly higher than the degree. On the other hand, the adjacency matrix allows testing whether two vertices are adjacent to each other in constant time; the adjacency list is slower to support this operation.

What does efficiency of the operations they perform refer to ?? What type of operations???

What does two vertices are adjacent to each other in constant time mean and are there any practical usage of knowing if two vertices are adjacent to each other???

Upvotes: 1

Views: 351

Answers (1)

pmr
pmr

Reputation: 59841

  1. Yes, you can also implement it explicitly using pointers to other nodes.
  2. listS consume more memory and are not random access, but handles (iterators) to elements stay valid on insertion and deletion; vectorS are memory efficient, random access, but invalidate handles (iterators) get invalidated on insertion and deletion; mapS usually consume more memory, don't iterate slower, handles (iterators) usually stay valid on insertion and deletion; look up of child nodes can be very fast. This is really the general difference between those containers and not very graph specific.
  3. The operations are explicitly given: listing neighbors and testing adjacency. Both have different complexities depending on the graph implementation.

two vertices are adjacent to each other just means that there is a direct edge between two nodes. To do that in constant time means that the operation is independent of how many neighbors each node has. As practical purposes go: Yes, tons of them. You might want to know if a city is connected to another city by a direct street. You might want to know if two vertices have an edge before collapsing it etc.

As you are talking C++ I would highly encourage you to have a look at some of the good graph libraries like Boost.Graph or Lemon.

Upvotes: 2

Related Questions