What is Graph?
A set of items connected by edges, each item is called a vertex or node. Formally, a graph is a set of vertices and a binary relation between vertices, adjacency.
A graph is a data structure that consists of two components:
1. A finite set of vertices also called as nodes.
2. A finite set of the ordered pair of the form (u, v) called as an edge. The pair is ordered because (u, v) is not same as (v, u) in case of a directed graph (di-graph). The pair of the form (u, v) indicates that there is an edge from vertex u to vertex v. The edges may contain weight/value/cost.
Graphs are used to represent many real life applications: Graphs are used to represent networks. The networks may include paths in a city or telephone network or circuit network. Graphs are also used in social networks like linkedIn, Facebook.
Facebook: Each user is represented as a vertex and two people are friends when there is an edge between two vertices. Similarly, friend suggestion also uses graph theory concept.
Google Maps: Various locations are represented as vertices and the roads are represented as edges and graph theory is used to find the shortest path between two nodes.
Recommendations on e-commerce websites: The “Recommendations for you” section on various e-commerce websites uses graph theory to recommend items of similar type to user’s choice.
Graph theory is also used to study molecules in chemistry and physics.
Most commonly used representations of the graph:
1. Adjacency Matrix
2. Adjacency List
Adjacency Matrix is a 2D array of size V x V where V is the number of vertices in a graph.
Let the 2D array be graph, a slot graph[i][j] = 1 indicates that there is an edge from vertex i to vertex j. Adjacency matrix for undirected graph is always symmetric. For weighted graphs, if graph [i][j] = w, then there is an edge from vertex i to vertex j with weight w in Adjacency Matrix.
Pros: Representation is easier to implement and follow. Removing an edge takes O(1) time. Queries like whether there is an edge from vertex ‘u’ to vertex ‘v’ are efficient and can be done O(1).
Cons: It consumes more space O(V^2). Even if the graph is sparse (contains less number of edges), it consumes the same space. Adding a new vertex is O(V^2) time.
An array of linked lists is used and the size of the array is equal to the number of vertices.
Let the array be array. An entry array[i] represents the linked list of vertices adjacent to the ith vertex. This representation can also be used to represent a weighted graph. The weights of edges can be stored in nodes of linked lists.
Pros: Saves space O(|V|+|E|). In the worst case, there can be C(V, 2) number of edges in a graph thus consuming O(V^2) space. Adding a vertex is easier.