Graph Data Structure
Graph is a non-linear data structure consisting of vertices and edges. The vertices are sometimes also referred to as nodes and the edges are lines or arcs that connect any two nodes in the graph. More formally a Graph is composed of a set of vertices (V) and a set of edges (E). The graph is denoted by G(V, E).
Imagine a game of football as a web of connections, where players are the nodes and their interactions on the field are the edges. This web of connections is exactly what a graph data structure represents, and it’s the key to unlocking insights into team performance and player dynamics in sports.
Components of Graph Data Structure
Vertices: Vertices are the fundamental units of the graph. Sometimes, vertices are also known as vertex or nodes. Every node/vertex can be labeled or unlabelled.
Edges: Edges are drawn or used to connect two nodes of the graph. It can be ordered pair of nodes in a directed graph. Edges can connect any two nodes in any possible way. There are no rules. Sometimes, edges are also known as arcs. Every edge can be labelled/unlabelled.
Components of Graph Data Structure
Vertices: Vertices are the fundamental units of the graph. Sometimes, vertices are also known as vertex or nodes. Every node/vertex can be labeled or unlabelled.
Edges: Edges are drawn or used to connect two nodes of the graph. It can be ordered pair of nodes in a directed graph. Edges can connect any two nodes in any possible way. There are no rules. Sometimes, edges are also known as arcs. Every edge can be labelled/unlabelled.
Types Of Graph Data Structure
1. Null Graph: A graph is known as a null graph if there are no edges in the graph.
2. Trivial Graph: Graph having only a single vertex, it is also the smallest graph possible.
3. Undirected Graph: A graph in which edges do not have any direction. That is the nodes are unordered pairs in the definition of every edge.
4. Directed Graph: A graph in which edge has direction. That is the nodes are ordered pairs in the definition of every edge.
5. Connected Graph: The graph in which from one node we can visit any other node in the graph is known as a connected graph.
6. Disconnected Graph: The graph in which at least one node is not reachable from a node is known as a disconnected graph.
7. Regular Graph: The graph in which the degree of every vertex is equal to K is called K regular graph.
8. Complete Graph: The graph in which from each node there is an edge to each other node.
9. Cycle Graph: The graph in which the graph is a cycle in itself, the degree of each vertex is 2.
10. Cyclic Graph: A graph containing at least one cycle is known as a Cyclic graph.
11. Directed Acyclic Graph: A Directed Graph that does not contain any cycle.
12. Bipartite Graph: A graph in which vertex can be divided into two sets such that vertex in each set does not contain any edge between them.
13. Weighted Graph: A graph in which the edges are already specified with suitable weight is known as a weighted graph. Weighted graphs can be further classified as directed weighted graphs and undirected weighted graphs.
Representation of Graph Data Structure
There are two ways to store a graph:
- Adjacency Matrix
- Adjacency List
Adjacency Matrix Representation of Graph Data Structure
In this method, the graph is stored in the form of the 2D matrix where rows and columns denote vertices. Each entry in the matrix represents the weight of the edge between those vertices.
Below is the implementation of Graph Data Structure represented using Adjacency Matrix:
#include <iostream>
#include <vector>
using namespace std;
vector<vector<int> >
createAdjacencyMatrix(vector<vector<int> >& graph,
int numVertices)
{
// Initialize the adjacency matrix with zeros
vector<vector<int> > adjMatrix(
numVertices, vector<int>(numVertices, 0));
// Fill the adjacency matrix based on the edges in the
// graph
for (int i = 0; i < numVertices; ++i) {
for (int j = 0; j < numVertices; ++j) {
if (graph[i][j] == 1) {
adjMatrix[i][j] = 1;
adjMatrix[j][i]
= 1; // For undirected graph, set
// symmetric entries
}
}
}
return adjMatrix;
}
int main()
{
// The indices represent the vertices, and the values
// are lists of neighboring vertices
vector<vector<int> > graph = { { 0, 1, 0, 0 },
{ 1, 0, 1, 0 },
{ 0, 1, 0, 1 },
{ 0, 0, 1, 0 } };
int numVertices = graph.size();
// Create the adjacency matrix
vector<vector<int> > adjMatrix
= createAdjacencyMatrix(graph, numVertices);
// Print the adjacency matrix
for (int i = 0; i < numVertices; ++i) {
for (int j = 0; j < numVertices; ++j) {
cout << adjMatrix[i][j] << " ";
}
cout << endl;
}
return 0;
}
Adjacency List Representation of Graph
This graph is represented as a collection of linked lists. There is an array of pointer which points to the edges connected to that vertex.
Below is the implementation of Graph Data Structure represented using Adjacency List:
#include <bits/stdc++.h>
using namespace std;
vector<vector<int>> createAdjacencyList(vector<vector<int> >& edges, int numVertices)
{
// Initialize the adjacency list
vector<vector<int> > adjList(numVertices);
// Fill the adjacency list based on the edges in the
// graph
for (int i=0; i < edges.size(); i++) {
int u = edges[i][0];
int v = edges[i][1];
// Since the graph is undirected, therefore we push the edges in both the directions
adjList[u].push_back(v);
adjList[v].push_back(u);
}
return adjList;
}
int main()
{
// Undirected Graph of 4 nodes
int numVertices = 4;
vector<vector<int>> edges = {{0, 1}, {0, 2}, {1, 2}, {2, 3}, {3, 1}};
// Create the adjacency List
vector<vector<int>> adjList = createAdjacencyList(edges, numVertices);
// Print the adjacency List
for (int i = 0; i < numVertices; ++i) {
cout << i << " -> ";
for (int j = 0; j < adjList[i].size(); ++j) {
cout << adjList[i][j] << " ";
}
cout << endl;
}
return 0;
}
Output:
0 -> 1 2
1 -> 0 2 3
2 -> 0 1 3
3 -> 2 1
Comparison between Adjacency Matrix and Adjacency List
When the graph contains a large number of edges then it is good to store it as a matrix because only some entries in the matrix will be empty. An algorithm such as Prim’s and Dijkstra adjacency matrix is used to have less complexity.
| Action |
Adjacency Matrix |
Adjacency List |
| Adding Edge |
O(1) |
O(1) |
| Removing an edge |
O(1) |
O(N) |
| Initializing |
O(N*N) |
O(N) |
Graph Data Structure
Graph is a non-linear data structure consisting of vertices and edges. The vertices are sometimes also referred to as nodes and the edges are lines or arcs that connect any two nodes in the graph. More formally a Graph is composed of a set of vertices (V) and a set of edges (E). The graph is denoted by G(V, E).
Imagine a game of football as a web of connections, where players are the nodes and their interactions on the field are the edges. This web of connections is exactly what a graph data structure represents, and it’s the key to unlocking insights into team performance and player dynamics in sports.
Components of Graph Data Structure
Vertices: Vertices are the fundamental units of the graph. Sometimes, vertices are also known as vertex or nodes. Every node/vertex can be labeled or unlabelled.
Edges: Edges are drawn or used to connect two nodes of the graph. It can be ordered pair of nodes in a directed graph. Edges can connect any two nodes in any possible way. There are no rules. Sometimes, edges are also known as arcs. Every edge can be labelled/unlabelled.
Types Of Graph Data Structure
1. Null Graph: A graph is known as a null graph if there are no edges in the graph.
2. Trivial Graph: Graph having only a single vertex, it is also the smallest graph possible.
3. Undirected Graph: A graph in which edges do not have any direction. That is the nodes are unordered pairs in the definition of every edge.
4. Directed Graph: A graph in which edge has direction. That is the nodes are ordered pairs in the definition of every edge.
5. Connected Graph: The graph in which from one node we can visit any other node in the graph is known as a connected graph.
6. Disconnected Graph: The graph in which at least one node is not reachable from a node is known as a disconnected graph.
7. Regular Graph: The graph in which the degree of every vertex is equal to K is called K regular graph.
8. Complete Graph: The graph in which from each node there is an edge to each other node.
9. Cycle Graph: The graph in which the graph is a cycle in itself, the degree of each vertex is 2.
10. Cyclic Graph: A graph containing at least one cycle is known as a Cyclic graph.
11. Directed Acyclic Graph: A Directed Graph that does not contain any cycle.
12. Bipartite Graph: A graph in which vertex can be divided into two sets such that vertex in each set does not contain any edge between them.
13. Weighted Graph: A graph in which the edges are already specified with suitable weight is known as a weighted graph. Weighted graphs can be further classified as directed weighted graphs and undirected weighted graphs.
Representation of Graph Data Structure
There are two ways to store a graph:
- Adjacency Matrix
- Adjacency List
Adjacency Matrix Representation of Graph Data Structure
In this method, the graph is stored in the form of the 2D matrix where rows and columns denote vertices. Each entry in the matrix represents the weight of the edge between those vertices.
Below is the implementation of Graph Data Structure represented using Adjacency Matrix:
#include <iostream>
#include <vector>
using namespace std;
vector<vector<int> >
createAdjacencyMatrix(vector<vector<int> >& graph,
int numVertices)
{
// Initialize the adjacency matrix with zeros
vector<vector<int> > adjMatrix(
numVertices, vector<int>(numVertices, 0));
// Fill the adjacency matrix based on the edges in the
// graph
for (int i = 0; i < numVertices; ++i) {
for (int j = 0; j < numVertices; ++j) {
if (graph[i][j] == 1) {
adjMatrix[i][j] = 1;
adjMatrix[j][i]
= 1; // For undirected graph, set
// symmetric entries
}
}
}
return adjMatrix;
}
int main()
{
// The indices represent the vertices, and the values
// are lists of neighboring vertices
vector<vector<int> > graph = { { 0, 1, 0, 0 },
{ 1, 0, 1, 0 },
{ 0, 1, 0, 1 },
{ 0, 0, 1, 0 } };
int numVertices = graph.size();
// Create the adjacency matrix
vector<vector<int> > adjMatrix
= createAdjacencyMatrix(graph, numVertices);
// Print the adjacency matrix
for (int i = 0; i < numVertices; ++i) {
for (int j = 0; j < numVertices; ++j) {
cout << adjMatrix[i][j] << " ";
}
cout << endl;
}
return 0;
}
Adjacency List Representation of Graph
This graph is represented as a collection of linked lists. There is an array of pointer which points to the edges connected to that vertex.
Below is the implementation of Graph Data Structure represented using Adjacency List:
#include <bits/stdc++.h>
using namespace std;
vector<vector<int>> createAdjacencyList(vector<vector<int> >& edges, int numVertices)
{
// Initialize the adjacency list
vector<vector<int> > adjList(numVertices);
// Fill the adjacency list based on the edges in the
// graph
for (int i=0; i < edges.size(); i++) {
int u = edges[i][0];
int v = edges[i][1];
// Since the graph is undirected, therefore we push the edges in both the directions
adjList[u].push_back(v);
adjList[v].push_back(u);
}
return adjList;
}
int main()
{
// Undirected Graph of 4 nodes
int numVertices = 4;
vector<vector<int>> edges = {{0, 1}, {0, 2}, {1, 2}, {2, 3}, {3, 1}};
// Create the adjacency List
vector<vector<int>> adjList = createAdjacencyList(edges, numVertices);
// Print the adjacency List
for (int i = 0; i < numVertices; ++i) {
cout << i << " -> ";
for (int j = 0; j < adjList[i].size(); ++j) {
cout << adjList[i][j] << " ";
}
cout << endl;
}
return 0;
}
Output:
0 -> 1 2
1 -> 0 2 3
2 -> 0 1 3
3 -> 2 1
Comparison between Adjacency Matrix and Adjacency List
When the graph contains a large number of edges then it is good to store it as a matrix because only some entries in the matrix will be empty. An algorithm such as Prim’s and Dijkstra adjacency matrix is used to have less complexity.
| Action |
Adjacency Matrix |
Adjacency List |
| Adding Edge |
O(1) |
O(1) |
| Removing an edge |
O(1) |
O(N) |
| Initializing |
O(N*N) |
O(N) |
Basic Operations on Graph Data Structure
Below are the basic operations on the graph:
- Insertion or Deletion of Nodes in the graph
- Add and Remove vertex in Adjacency List representation of Graph
- Add and Remove vertex in Adjacency Matrix representation of Graph
- Insertion or Deletion of Edges in the graph
- Add and Remove Edge in Adjacency List representation of a Graph
- Add and Remove Edge in Adjacency Matrix representation of a Graph
- Searching in Graph Data Structure- Search an entity in the graph.
- Traversal of Graph Data Structure- Traversing all the nodes in the graph.
Advantages of Graph Data Structure
Graph Data Structure is used to represent a wide range of relationships and data structures.
They can be used to model and solve a wide range of problems, including pathfinding, data clustering, network analysis, and machine learning.
Graph algorithms are often very efficient and can be used to solve complex problems quickly and effectively.
Graph Data Structure can be used to represent complex data structures in a simple and intuitive way, making them easier to understand and analyze.
Disadvantages of Graph Data Structure
Graph Data Structure can be complex and difficult to understand, especially for people who are not familiar with graph theory or related algorithms.
Creating and manipulating graphs can be computationally expensive, especially for very large or complex graphs.
Graph algorithms can be difficult to design and implement correctly, and can be prone to bugs and errors.
Graph Data Structure can be difficult to visualize and analyze, especially for very large or complex graphs, which can make it challenging to extract meaningful insights from the data.