Graph Basics
Graph Basics
Definition of a Graph
A graph is a data structure used to model pairwise relations between objects. A graph G is defined as:
G = (V, E)
Basic Terminology
Term Description
Cycle A path where the starting and ending vertices are the same.
Connected Graph A graph is connected if there is a path between every pair of vertices.
Disconnected Graph A graph with at least two vertices with no path connecting them.
Unweighted Graph All edges are assumed to have equal weight (or no weights).
Directed Graph (Digraph) Edges have a direction, going from one vertex to another.
Multigraph A graph with multiple edges between the same pair of vertices.
Graph Representation
1. Adjacency Matrix
o A 2D array of size V x V.
o If there is an edge from vertex i to vertex j, then matrix[i][j] = 1 (or weight).
o Pros: Easy to implement and check if an edge exists.
o Cons: Requires O(V²) space.
2. Adjacency List
o An array of lists.
o Each vertex has a list of all vertices it is adjacent to.
o Pros: Space efficient for sparse graphs (O(V + E)).
o Cons: Slightly more complex to implement.
3. Edge List
o A list of all edges represented as pairs/triplets (u, v) or (u, v, w).
o Useful for algorithms like Kruskal’s.
Types of Graphs
Example
Adjacency List:
A→B→C
B→D
C→
D→
Adjacency Matrix:
ABCD
A[0110]
B[0001]
C[0000]
D[0000]