Graphs
Graphs
1. Introduction
A graph is a non-linear data structure consisting of nodes (or vertices) and edges (connections
between the nodes). Graphs are used to model relationships, such as networks, social connections,
or paths between cities. They are widely used in many fields like computer science, operations
research, and social networks.
2. Basic Terminology
• Cycle: A path where the first and last vertices are the same.
o Undirected: Edges do not have a direction (no arrows, just a connection between
two vertices).
3. Types of Graphs
Type Description
Vertices can be divided into two disjoint sets such that no two vertices
Bipartite Graph
within the same set are adjacent.
• Adjacency Matrix: A 2D array A[][] where A[i][j] is 1 (or the weight) if there is an edge
between vertex i and vertex j, and 0 otherwise.
• Adjacency List: An array of lists where each list represents the neighbors of a vertex.
• Edge List: A list of all edges in the graph, where each edge is represented as a pair of
vertices.
Algorithm Description
Depth-First Search
Explores as far as possible along a branch before backtracking.
(DFS)
Breadth-First Search Explores all neighbors at the present depth level before moving on to nodes
(BFS) at the next depth level.
DFS (Pseudocode):
python
CopyEdit
visited.add(node)
BFS (Pseudocode):
python
CopyEdit
visited = set()
queue = deque([start])
visited.add(start)
while queue:
vertex = queue.popleft()
visited.add(neighbor)
queue.append(neighbor)
• Dijkstra’s Algorithm: Used to find the shortest path in a graph with non-negative edge
weights.
• Bellman-Ford Algorithm: Can handle negative edge weights, but slower than Dijkstra's.
8. Advantages
• Efficient for sparse and large datasets: Graph algorithms scale well for large and sparse
graphs.
• Versatile structure: Can be used to represent many kinds of data and relationships.
9. Disadvantages
• Complexity: Graph algorithms can be complex and require significant computation time for
large graphs.
• Algorithmic challenges: Some graph problems are NP-complete (e.g., the traveling
salesman problem).
10. Applications
Imagine a city map with locations (vertices) connected by roads (edges). Finding the shortest path
between two locations is a graph problem that can be solved using algorithms like Dijkstra's.