
Graphs are fundamental data structures in various computer science applications, including network design, social network analysis, and route planning. Understanding graph terminology is crucial for effectively navigating and manipulating graph data structures. In this article, we will discuss the graph terminology used in the data structure.
Graph (G): A non-linear data structure consisting of a set of vertices (nodes) and a set of edges connecting these vertices. Represented as G = (V, E), where V is the set of vertices and E is the set of edges.
Vertex (Node): A fundamental unit in a graph, representing an entity or object.
Edge: A connection between two vertices. Edges can be either directed or undirected.
Directed Edge: An edge with a specific direction, indicating a one-way connection from a source vertex to a destination vertex.
Undirected Edge: An edge without a specific direction, representing a bidirectional connection between two vertices.
Degree of a Vertex: The number of edges incident to a vertex.
In-degree (Directed Graph): The number of incoming edges to a vertex.
Out-degree (Directed Graph): The number of outgoing edges from a vertex.
Path: A sequence of vertices where each adjacent pair is connected by an edge.
Cycle: A path that starts and ends at the same vertex, with all other vertices in the path distinct.
Connected Graph: A graph where there is a path between every pair of vertices.
Disconnected Graph: A graph that is not connected; it can be divided into two or more connected components.
Connected Component: A subgraph in which any two vertices are connected to each other by paths, and which is connected to no additional vertices in the supergraph.
Adjacency: Two vertices are adjacent if they are connected by an edge.
Incident: An edge is incident to a vertex if the vertex is one of the endpoints of the edge.
Subgraph: A graph formed by a subset of the vertices and edges of a larger graph.
Spanning Tree: A subgraph of a connected, undirected graph that is a tree and includes all the vertices of the original graph.
Forest: A collection of disjoint trees.
Two most common ways to represent a graph : For simplicity, we are going to consider only unweighted graphs
Adjacency Matrix
Adjacency List
Adjacency Matrix Representation
An adjacency matrix is a way of representing a graph as a boolean matrix of (0's and 1's).
Let's assume there are n vertices in the graph So, create a 2D matrix adjMat[n][n] having dimension n x n.
If there is an edge from vertex i to j, mark adjMat[i][j] as 1.
If there is no edge from vertex i to j, mark adjMat[i][j] as 0.
Adjacency List Representation
An array of Lists is used to store edges between two vertices. The size of array is equal to the number of vertices (i.e, n). Each index in this array represents a specific vertex in the graph. The entry at the index i of the array contains a linked list containing the vertices that are adjacent to vertex i. Let's assume there are n vertices in the graph So, create an array of list of size n as adjList[n].
adjList[0] will have all the nodes which are connected (neighbour) to vertex 0.
adjList[1] will have all the nodes which are connected (neighbour) to vertex 1 and so on.
Graph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social network, a computer network, a network of locations used in GPS and many more examples where different nodes or vertices are connected without any hierarchic or constraint on structure.
Dijkstra's shortest path algorithm was invented in 1956 by the Dutch computer scientist Edsger W. Dijkstra during a twenty minutes coffee break, while out shopping with his fiancée in Amsterdam.
The reason for inventing the algorithm was to test a new computer called ARMAC.
Dijkstra's algorithm finds the shortest path from one vertex to all other vertices.
It does so by repeatedly selecting the nearest unvisited vertex and calculating the distance to all the unvisited neighboring vertices.
Step-by-Step Implementation
Set dist[source]=0 and all other distances as infinity.
Push the source node into the min heap as a pair <distance, node> → i.e., <0, source>.
Pop the top element (node with the smallest distance) from the min heap.
For each adjacent neighbor of the current node:
Calculate the distance using the formula:
dist[v] = dist[u] + weight[u][v]
If this new distance is shorter than the current dist[v], update it.
Push the updated pair <dist[v], v> into the min heap
Repeat step 3 until the min heap is empty.
Return the distance array, which holds the shortest distance from the source to all nodes.
Time Complexity: O(E*logV), Where E is the number of edges and V is the number of vertices.
Auxiliary Space: O(V), Where V is the number of vertices, We do not count the adjacency list in auxiliary space as it is necessary for representing the input graph.
Topological Sort is a linear ordering of vertices in a Directed Acyclic Graph (DAG) such that for every directed edge u → v, vertex u appears before v in the ordering.
Applies only to DAGs (Directed Acyclic Graphs), and is not possible for cyclic or undirected graphs.
It doesn’t “traverse” all vertices like BFS/DFS; instead, it represents dependency ordering between them.
Used in problems like task scheduling, build order, course prerequisite ordering, etc.
Topological Sorting in Directed Acyclic Graphs (DAGs)
DAGs are graphs where each edge is directed and no cycle exists in the graph.
Undirected Graph:
Every edge u–v can be seen as both u→v and v→u, so you can’t decide which one should come first.
Cyclic Graph: If graph contains the cycle, u→v→w→u, then you’d need u before v, v before w, and w before u — impossible to satisfy.
Topological order may not be Unique:
Topological sort represents all possible ordering satisfying the condition that if there is an edge between u→v, u comes before v in the ordering. Any ordering that satisfies this for all edges(u->v) is valid.
Algorithm
Following are the steps to perform topological sorting using DFS:
Call the DFS function for a vertex u.
In the DFS function, mark the vertex u as visited.
For every adjacent vertex v of u, if v is not visited, then call the DFS function for vertex v.
After visiting all the adjacent vertices of vertex u, add the vertex u to the topological order list.
Time Complexity of Topological Sort
When using Depth First Search (DFS) for topological sorting, the time complexity is O(V + E), where V is the number of vertices and E is the number of edges in the graph. This is because we visit each node once and explore all its edges.
Advantages of Topological Sort:
Helps in scheduling tasks or events based on dependencies.
Detects cycles in a directed graph.
Efficient for solving problems with precedence constraints.
Disadvantages of Topological Sort:
Only applicable to directed acyclic graphs (DAGs), not suitable for cyclic graphs.
May not be unique, multiple valid topological orderings can exist.
Applications of Topological Sort
Topological sorting has many applications in various fields. Some of the applications of topological sort are:
Task Scheduling: Used to schedule tasks based on dependencies. Each task is a node, and dependencies are edges. This ensures tasks are executed in the correct order.
Course Prerequisites: Helps in deciding the order of taking courses. Courses are nodes, and prerequisites are edges, ensuring prerequisites are completed first.
Build Systems: Used in software build processes to determine the correct sequence for compiling files based on dependencies.
Network Routing: Helps in routing packets through a network by determining the correct order of processing based on connections between routers.
A spanning tree is a subset of Graph G, which has all the vertices covered with minimum possible number of edges. Hence, a spanning tree does not have cycles and it cannot be disconnected..
By this definition, we can draw a conclusion that every connected and undirected Graph G has at least one spanning tree. A disconnected graph does not have any spanning tree, as it cannot be spanned to all its vertices.
Properties of a Spanning Tree
A Spanning tree does not exist for a disconnected graph.
For a connected graph having N vertices then the number of edges in the spanning tree for that graph will be N-1.
A Spanning tree does not have any cycle.
We can construct a spanning tree for a complete graph by removing E-N+1 edges, where E is the number of Edges and N is the number of vertices.
Cayley's Formula: It states that the number of spanning trees in a complete graph with N vertices is NN−2NN−2
For example: N=4, then maximum number of spanning tree possible =44−244−2 = 16 (shown in the above image).
Mathematical Properties of Spanning Tree
Spanning tree has n-1 edges, where n is the number of nodes (vertices).
From a complete graph, by removing maximum e - n + 1 edges, we can construct a spanning tree.
A complete graph can have maximum nn-2 number of spanning trees.
Thus, we can conclude that spanning trees are a subset of connected Graph G and disconnected graphs do not have spanning tree.
Application of Spanning Tree
Spanning tree is basically used to find a minimum path to connect all nodes in a graph. Common application of spanning trees are −
Civil Network Planning
Computer Network Routing Protocol
Cluster Analysis
A minimum spanning tree (MST) is defined as a spanning tree that has the minimum weight among all the possible spanning trees.
Properties of Minimum Spanning Tree:
A minimum spanning tree connects all the vertices in the graph, ensuring that there is a path between any pair of nodes.
An MST is acyclic, meaning it contains no cycles. This property ensures that it remains a tree and not a graph with loops.
An MST with V vertices (where V is the number of vertices in the original graph) will have exactly V - 1 edges, where V is the number of vertices.
An MST is optimal for minimizing the total edge weight, but it may not necessarily be unique.
The cut property states that if you take any cut (a partition of the vertices into two sets) in the original graph and consider the minimum-weight edge that crosses the cut, that edge is part of the MST.
Real World Application of A Minimum Spanning Tree:
Network design: Spanning trees can be used in network design to find the minimum number of connections required to connect all nodes. Minimum spanning trees, in particular, can help minimize the cost of the connections by selecting the cheapest edges.
Image processing: Spanning trees can be used in image processing to identify regions of similar intensity or color, which can be useful for segmentation and classification tasks.
Social network analysis: Spanning trees and minimum spanning trees can be used in social network analysis to identify important connections and relationships among individuals or groups.
Kruskal's Minimum Spanning Tree (MST) algorithm is to connect all the vertices of a graph with the minimum total edge weight while avoiding cycles. This algorithm employs a greedy approach, meaning it makes locally optimal choices at each step to achieve a globally optimal solution.
Algorithm:
First, it sorts all the edges of the graph by their weights,
Then starts the iterations of finding the spanning tree.
At each iteration, the algorithm adds the next lowest-weight edge one by one, such that the edges picked until now does not form a cycle.
This algorithm can be implemented efficiently using a DSU ( Disjoint-Set ) data structure to keep track of the connected components of the graph. This is used in a variety of practical applications such as network design, clustering, and data analysis.
Minimum Spanning Tree (MST) is to build the MST incrementally by starting with a single vertex and gradually extending the tree by adding the closest neighbouring vertex at each step.
Algorithm:
It starts by selecting an arbitrary vertex and then adding it to the MST.
Then, it repeatedly checks for the minimum edge weight that connects one vertex of MST to another vertex that is not yet in the MST.
This process is continued until all the vertices are included in the MST.
To efficiently select the minimum weight edge for each iteration, this algorithm uses priority_queue to store the vertices sorted by their minimum edge weight currently. It also simultaneously keeps track of the MST using an array or other data structure suitable considering the data type it is storing.
This algorithm can be used in various scenarios such as image segmentation based on color, texture, or other features. For Routing, as in finding the shortest path between two points for a delivery truck to follow.
Social media analysis: Social media platforms generate vast amounts of data in real-time, which can be analyzed using graphs to identify trends, sentiment, and key influencers. This can be useful for marketing, customer service, and reputation management.
Network monitoring: Graphs can be used to monitor network traffic in real-time, allowing network administrators to identify potential bottlenecks, security threats, and other issues. This is critical for ensuring the smooth operation of complex networks.
Financial trading: Graphs can be used to analyze real-time financial data, such as stock prices and market trends, to identify patterns and make trading decisions. This is particularly important for high-frequency trading, where even small delays can have a significant impact on profits.
Internet of Things (IoT) management: IoT devices generate vast amounts of data in real-time, which can be analyzed using graphs to identify patterns, optimize performance, and detect anomalies. This is important for managing large-scale IoT deployments.
Autonomous vehicles: Graphs can be used to model the real-time environment around autonomous vehicles, allowing them to navigate safely and efficiently. This requires real-time data from sensors and other sources, which can be processed using graph algorithms.
Disease surveillance: Graphs can be used to model the spread of infectious diseases in real-time, allowing health officials to identify outbreaks and implement effective containment strategies. This is particularly important during pandemics or other public health emergencies.
The best example of graphs in the real world is Facebook. Each person on Facebook is a node and is connected through edges. Thus, A is a friend of B. B is a friend of C, and so on.
Advantages of Graph:
Representing complex data: Graphs are effective tools for representing complex data, especially when the relationships between the data points are not straightforward. They can help to uncover patterns, trends, and insights that may be difficult to see using other methods.
Efficient data processing: Graphs can be processed efficiently using graph algorithms, which are specifically designed to work with graph data structures. This makes it possible to perform complex operations on large datasets quickly and effectively.
Network analysis: Graphs are commonly used in network analysis to study relationships between individuals or organizations, as well as to identify important nodes and edges in a network. This is useful in a variety of fields, including social sciences, business, and marketing.
Pathfinding: Graphs can be used to find the shortest path between two points, which is a common problem in computer science, logistics, and transportation planning.
Visualization: Graphs are highly visual, making it easy to communicate complex data and relationships in a clear and concise way. This makes them useful for presentations, reports, and data analysis.
Machine learning: Graphs can be used in machine learning to model complex relationships between variables, such as in recommendation systems or fraud detection.
Graphs are used in computer science to depict the flow of computation.
Users on Facebook are referred to as vertices, and if they are friends, there is an edge connecting them. The Friend Suggestion system on Facebook is based on graph theory.
You come across the Resources Allocation Graph in the Operating System, where each process and resource are regarded vertically. Edges are drawn from resources to assigned functions or from the requesting process to the desired resources. A stalemate will develop if this results in the establishment of a cycle.
Web pages are referred to as vertices on the World Wide Web. Suppose there is a link from page A to page B that can represent an edge. this application is an illustration of a directed graph.
Graph transformation systems manipulate graphs in memory using rules, Graph databases store and query graph-structured data in a transaction-safe, perment manner.
Disadvantages of Graph:
Limited representation: Graphs can only represent relationships between objects, and not their properties or attributes. This means that in order to fully understand the data, it may be necessary to supplement the graph with additional information.
Difficulty in interpretation: Graphs can be difficult to interpret, especially if they are large or complex. This can make it challenging to extract meaningful insights from the data, and may require advanced analytical techniques or domain expertise.
Scalability issues: As the number of nodes and edges in a graph increases, the processing time and memory required to analyze it also increases. This can make it difficult to work with large or complex graphs.
Data quality issues: Graphs are only as good as the data they are based on, and if the data is incomplete, inconsistent, or inaccurate, the graph may not accurately reflect the relationships between objects.
Lack of standardization: There are many different types of graphs, and each has its own strengths and weaknesses. This can make it difficult to compare graphs from different sources, or to choose the best type of graph for a given analysis.
Privacy concerns: Graphs can reveal sensitive information about individuals or organizations, which can raise privacy concerns, especially in social network analysis or marketing.
The Graph Data Structures and Algorithms course provides an in-depth understanding of how graphs are used to represent and solve real-world computational problems. Students will explore the fundamental concepts of graphs, including vertices, edges, degrees, adjacency, and connectivity, and will learn to differentiate between various types of graphs such as directed, undirected, weighted, and unweighted. The course emphasizes practical learning through the implementation of key graph algorithms, including traversal techniques (BFS, DFS), shortest path algorithms (Dijkstra’s, Bellman-Ford, Floyd-Warshall), and optimization algorithms (Prim’s and Kruskal’s for Minimum Spanning Trees). Learners will also study topological sorting, connectivity analysis, and real-world applications in network design, data analysis, and cybersecurity. By the end of the course, students will be able to model complex systems using graphs, select appropriate algorithms for given problems, and analyze their performance in terms of time and space complexity.