- Introduction to Adjacency List.
- Some STL Componenets required to make Adjacency List:
- Vector
- Pair
- Map
- Implementation in C++.
-
Introduction to Adjacency List :
According to wikipedia: In graph theory and computer science, an adjacency list is a collection of unordered lists used to represent a finite graph. Each list describes the set of neighbors of a vertex in the graph. This is one of several commonly used representations of graphs for use in computer programs.
We can solve many graph problems much efficiently using Adjacency list representation of a graph as compared to Adjacency Matrix. Example we can run DFS on adjacency List in O(E + V) time while it requires O(V * V) time for Adjacency Matrix. Here E = number of edges and V = number of vertices in a graph.
We can create Adjacency list by making out own classes and functions like addEdge(), removeEdge() etc which is not a good practice in competitive programming because we don't have enough time to write a lot of stuff. So most of the programmers don't use such cumbersome method.
Let's see what they use ! - Some STL Componenets required to make Adjacency List:
- Vector :Vectors are sequence containers representing arrays that can change in size. That's great ! we need not to specify the size of a vector. Let's see the implementation part: Click here if you want to learn more about vectors.
- Pair : As the name suggests, it is a data structure that can contain a pair of either same or different data types.
- Map : Hash Map in C++.Data is stored in the form of Key-Value pairs. We can insert, search, erase an element from map in O(logN) time.
You can learn about maps(STL) on Geeks For Geeks.
Practice this data structure on Hackerrank.
- Implementation : Its the time to create our own adjacency list for the following graph using the above cool data structures in C++: Click here to see input and output for this program. Remove all the comments from this program to see the actual length of this C++ program. :)
Congrats ! You now know how to create your Adjacency List in C++(in not more than 7-10 lines of code) for a given graph.
I am finding your blog quite useful.. Keep up the good work :)
ReplyDeleteA Computer Science portal for geeks. It contains well written, well thought and well explained computer science and programming articles, quizzes and practice/competitive programming/company interview Questions.
ReplyDeletewebsite: geeksforgeeks.org
A Computer Science portal for geeks. It contains well written, well thought and well
ReplyDeleteexplained computer science and programming articles, quizzes and practice/competitive
programming/company interview Questions.
website: geeksforgeeks.org
Thank you so much for the post you do. I like your post and all you share with us is up to date and quite informative, i would like to bookmark the page so i can come here again to read you, as you have done a wonderful job. coding chair
ReplyDelete