What is Graph and How to Represent it?
Real World Application and implementation in C++
Table of contents
Graphs are the mathematical structure to establish a relationship between different objects with the help of edges and vertices.
Edges: These are the lines that establish a relation between one object with another object in a graph. For Example Distance Between Two Points, Friend of Friend on Social Media .. etc
Vertices: These are objects which are present in the graph. For Example Nodes in the Network, Users in Social Networks, Molecules, etc
It is one of the most important Data structures because of its versatility, applicability to real-world problems, and significance in various fields of study.
So, Before moving to Graph first we should understand why Graphs are different from Trees.
A graph is a non-linear data structure like a tree but a tree establishes a hierarchical relationship where each node has one parent and zero and many children.
There are a few key differences from which we can say that Graph is not Tree or vice-versa.
Structure: A graph is a collection of nodes (vertices) and edges that connect the nodes. The edges can connect any two nodes, and there can be cycles in a graph. In contrast, a tree is a special type of graph where there is a single root node and all other nodes have exactly one parent, except for the root node. A tree structure forms a hierarchy, with each node having zero or more child nodes.
Types of relationships: A graph can represent any type of relationship between nodes, including bi-directional relationships, one-to-many relationships, many-to-many relationships, and cycles. In contrast, a tree represents a hierarchical relationship where each node has a single parent and zero or more children. Trees are useful for representing data with a clear hierarchical structure, such as file systems, organization charts, or family trees.
Traversals: Graphs and trees can both be traversed using algorithms such as depth-first search (DFS) and breadth-first search (BFS). However, the traversal order in a tree is well-defined and follows the hierarchical structure, while the traversal order in a graph depends on the algorithm and may not follow a clear pattern.
Application
Graphs are the unsung heroes of the technology world, quietly connecting everything from our online social lives to the electric impulses in our brains. Their importance cannot be overstated, as they are crucial in a vast array of real-world applications that demonstrate their versatility and power.
Social Networks: Social networks such as Facebook, Twitter, and LinkedIn are modeled as graphs, where individuals are represented as nodes and the connections between them as edges. Graph algorithms can be used to analyze social networks and study the patterns of connections, clustering, and influence.
Transportation Networks: Transportation networks such as roads, railways, and flight routes can be modeled as graphs, where cities are represented as nodes and the connections between them as edges. Graph algorithms can be used to find the shortest paths between two cities, optimize routes, and detect bottlenecks.
Molecular Structures: Chemical compounds and molecular structures can be represented as graphs, where atoms are represented as nodes and the chemical bonds between them as edges. Graph algorithms can be used to study the properties of molecules, such as their stability, reactivity, and shape.
Web Search: Search engines such as Google and Bing use graph algorithms to rank web pages based on their relevance and popularity. The web pages are represented as nodes and the hyperlinks between them as edges.
Computer Networks: Computer networks such as the Internet can be modeled as graphs, where computers and servers are represented as nodes and the connections between them as edges. Graph algorithms can be used to optimize network routing, detect failures, and improve network security.
Image Processing: Images and videos can be represented as graphs, where pixels or frames are represented as nodes and the connections between them as edges. Graph algorithms can be used for tasks such as image segmentation, object recognition, and motion detection.
Implementation in C++
There are two ways to represent graphs in Computer science and Mathematics and here are the following:
To represent a graph, you have several options depending on the nature of the graph and the purpose of the representation. Here are a few common methods:
Adjacency Matrix: An adjacency matrix is a square matrix used to represent a graph. Each cell in the matrix represents an edge between two vertices. If there is an edge between vertices i and j, the corresponding cell (i, j) or (j, i) is marked. This method is useful for dense graphs but can be memory-intensive for large graphs.
#include <iostream> #include <vector> using namespace std; const int MAX_VERTICES = 100; // Maximum number of vertices in the graph // Function to add an edge to the graph void addEdge(vector<vector<int>>& graph, int u, int v) { graph[u][v] = 1; graph[v][u] = 1; } // Function to print the adjacency matrix representation of the graph void printGraph(const vector<vector<int>>& graph, int vertices) { cout << "Adjacency matrix representation of the graph:" << endl; for (int i = 0; i < vertices; ++i) { for (int j = 0; j < vertices; ++j) { cout << graph[i][j] << " "; } cout << endl; } } int main() { int vertices = 5; // Number of vertices vector<vector<int>> graph(vertices, vector<int>(vertices, 0)); addEdge(graph, 0, 1); addEdge(graph, 0, 4); addEdge(graph, 1, 2); addEdge(graph, 1, 3); addEdge(graph, 1, 4); addEdge(graph, 2, 3); addEdge(graph, 3, 4); printGraph(graph, vertices); return 0; } /*Adjacency matrix representation of the graph: 0 1 0 0 1 1 0 1 1 1 0 1 0 1 0 0 1 1 0 1 1 1 0 1 0 */
Adjacency List: An adjacency list is a collection of lists or arrays used to represent a graph. Each vertex has a list containing its adjacent vertices. This method is memory-efficient for sparse graphs and allows for efficient traversal of the graph.
#include <iostream> #include <vector> using namespace std; // Function to add an edge to the graph void addEdge(vector<int> adj[], int u, int v) { adj[u].push_back(v); adj[v].push_back(u); } // Function to print the adjacency list representation of the graph void printGraph(vector<int> adj[], int V) { for (int v = 0; v < V; ++v) { cout << "Adjacency list of vertex " << v << ": "; for (auto x : adj[v]) cout << x << " "; cout << endl; } } int main() { int V = 5; // Number of vertices vector<int> adj[V]; addEdge(adj, 0, 1); addEdge(adj, 0, 4); addEdge(adj, 1, 2); addEdge(adj, 1, 3); addEdge(adj, 1, 4); addEdge(adj, 2, 3); addEdge(adj, 3, 4); printGraph(adj, V); return 0; } /* Adjacency list representation of the graph: Vertex 0: 1 4 Vertex 1: 0 2 3 4 Vertex 2: 1 3 Vertex 3: 1 2 4 Vertex 4: 0 1 3 */
Edge List: An edge list is a simple representation that lists all the edges in the graph. Each edge is represented as a pair of vertices. This method is straightforward but doesn't provide direct information about the adjacency of vertices.
```cpp #include #include #include
using namespace std;
// Function to print the edge list representation of the graph void printGraph(const vector>& edges) { cout << "Edge list representation of the graph:" << endl; for (const auto& edge : edges) { cout << edge.first << " - " << edge.second << endl; } }
int main() { vector> edges = { {0, 1}, {0, 4}, {1, 2}, {1, 3}, {1, 4}, {2, 3}, {3, 4} };
printGraph(edges);
return 0; }
/* Edge list representation of the graph: 0 - 1 0 - 4 1 - 2 1 - 3 1 - 4 2 - 3 3 - 4
*/ ```