Graphs
Graphs
1. Introduction to Graphs
A graph is a fundamental data structure in computer science, consisting of:
• Vertices (or Nodes): Represent entities.
• Edges: Represent the relationships between vertices.
Graphs are used to model networks, relationships, and interactions in various fields, such as social
networks, transportation systems, and the internet.
Formal Definition
A graph G is defined as: G=(V,E) Where:
• V is the set of vertices.
• E is the set of edges, represented as pairs (u,v) where u,v∈V.
2. Types of Graphs
Graphs can be classified based on their properties:
2.4 Trees
A tree is a special type of graph that is connected and acyclic.
3. Graph Representation
Graphs can be represented in memory using different methods:
4. Graph Traversal
Graph traversal is the process of visiting all vertices in a graph.
5. Graph Algorithms
5.1 Shortest Path Algorithms
1. Dijkstra's Algorithm:
• Finds the shortest path from a source to all other vertices in a weighted graph.
• Uses a priority queue.
2. Bellman-Ford Algorithm:
• Handles graphs with negative weights.
• Computes shortest paths by relaxing edges repeatedly.
3. Floyd-Warshall Algorithm:
• Finds shortest paths between all pairs of vertices.
6. Applications of Graphs
1. Social Networks: Modeling connections between individuals.
2. Transportation Networks: Optimizing routes in road and flight networks.
3. Web Graphs: Representing links between web pages.
4. Dependency Graphs: Scheduling tasks based on dependencies.
5. Network Flow: Solving problems like maximum flow in networks.
7. Complexity Analysis
Algorithm Time Complexity Space Complexity
DFS O(V+E) O(V)
BFS O(V+E) O(V)
Dijkstra’s Algorithm O(V2) or O((V+E)logV) (with a priority queue) O(V)
Kruskal’s Algorithm O(ElogE) O(V+E)
Prim’s Algorithm O(V2) or O((V+E)logV) O(V)
8. Real-World Example
Routing Algorithms
Graph-based routing algorithms like Dijkstra's are used in GPS navigation systems to find the
shortest path between two locations.
PageRank Algorithm
Google's PageRank algorithm models the web as a graph where pages are vertices, and hyperlinks
are directed edges.