Graphs and Types of Graphs
A graph is a non-linear data structure of vertices (nodes) connected by edges to model pairwise relationships. Types include directed, undirected, weighted, unweighted, cyclic, acyclic (DAG), connected, disconnected, complete, and bipartite graphs.
Theory & Explanation
Graphs, Types of Graphs & Graph Terminology
1. Definition of a Graph
A Graph G = (V, E) is a non-linear data structure consisting of a finite non-empty set of vertices (nodes) V and a set of edges (links) E connecting pairs of vertices to represent pairwise relationships. Unlike trees, a graph does not require a single designated root node and may contain cycles.
Graphs model road/metro networks, social connections, computer networks, dependency schedules, and state transitions. A simple undirected graph with |V| vertices has at most |V|(|V| - 1) / 2 edges, whereas a directed graph (without self-loops) has at most |V|(|V| - 1) edges.
2. Basic Terminology Used with Graphs
- Vertex (Node): Fundamental unit/entity in a graph (e.g., a city, user, or router).
- Edge: A connection between two vertices; written as
(u, v)in an undirected graph or<u, v>/u → vin a directed graph. - Adjacent Vertices (Neighbors): Two vertices connected directly by an edge.
- Incident Edge: An edge is said to be incident on the two vertices it connects.
- Degree (Undirected Graph): The number of edges incident to a vertex (a self-loop contributes
2to the degree in standard conventions). - In-Degree & Out-Degree (Directed Graph): In-degree of vertex
vis the number of incoming edges pointing tov; out-degree is the number of outgoing edges leavingv. - Self-Loop: An edge starting and ending at the same vertex, i.e.,
(u, u)oru → u. - Parallel (Multiple) Edges: Two or more edges connecting the same pair of vertices with the same orientation.
- Simple Graph: A graph with no self-loops and no parallel edges.
- Path & Simple Path: A sequence of vertices where consecutive vertices share an edge. A simple path repeats no vertices (except possibly start and end in a cycle).
- Cycle: A non-empty path that starts and ends at the same vertex without repeating edges.
- Connected vs. Disconnected Graph: An undirected graph is connected if there is a path between every pair of vertices; otherwise it is disconnected (made of connected components).
Graphical Representation of a Graph (HTML/CSS Diagram)
(A,B), (A,C), (B,D), (C,D) |
Neighbors of B: A, D |
Contains a cycle of length 4.
3. Types of Graphs with Definitions
- Undirected Graph: Edges have no direction;
(u, v)and(v, u)represent the same bidirectional link. - Directed Graph (Digraph): Edges have a specific direction from tail to head (
u → v). - Weighted Graph: Each edge carries a numerical value (weight/cost), such as distance, time, or bandwidth.
- Unweighted Graph: All edges are treated equally without numerical weights.
- Cyclic Graph: Contains at least one cycle.
- Acyclic Graph: Contains no cycles. A directed acyclic graph is called a DAG (used in task scheduling and topological sorting); a connected undirected acyclic graph is a Tree.
- Complete Graph (
Kn): A simple graph in which every pair of distinct vertices is connected by a unique edge. An undirected complete graph withnvertices hasn(n - 1) / 2edges. - Connected & Disconnected Graph: Every vertex is reachable from every other vertex in a connected graph; a disconnected graph has two or more isolated components.
- Bipartite Graph: Vertices can be partitioned into two disjoint sets
UandVsuch that every edge connects a vertex inUto a vertex inV(no edges withinUor withinV). - Sparse vs. Dense Graph: A sparse graph has relatively few edges (
|E|close to|V|), whereas a dense graph has many edges (|E|close to|V|2).
Graphical Representation: Common Graph Types
A → B).Has in-degree & out-degree.
e.g.,
A --(5)-- B.
Edges =
n(n - 1) / 2.
U & V; edges only between sets.
4. Graph Representation & C Implementation (Adjacency Matrix)
Graphs are commonly represented using an Adjacency Matrix (2D array of size V × V, good for dense graphs and O(1) edge lookup) or an Adjacency List (array of lists/linked lists, space-efficient O(|V| + |E|) for sparse graphs). Below is an undirected graph represented with an adjacency matrix in C:
#include <stdio.h>
#define V 4
void initGraph(int adj[V][V]) {
for (int i = 0; i < V; i++) {
for (int j = 0; j < V; j++) {
adj[i][j] = 0;
}
}
}
void addEdge(int adj[V][V], int u, int v) {
adj[u][v] = 1;
adj[v][u] = 1; // Undirected graph
}
void printMatrix(int adj[V][V]) {
printf("Adjacency Matrix:\n");
for (int i = 0; i < V; i++) {
for (int j = 0; j < V; j++) {
printf("%d ", adj[i][j]);
}
printf("\n");
}
}
int main() {
// Vertices: 0=A, 1=B, 2=C, 3=D
int adj[V][V];
initGraph(adj);
addEdge(adj, 0, 1); // A - B
addEdge(adj, 0, 2); // A - C
addEdge(adj, 1, 3); // B - D
addEdge(adj, 2, 3); // C - D
printMatrix(adj);
for (int i = 0; i < V; i++) {
int deg = 0;
for (int j = 0; j < V; j++) {
deg += adj[i][j];
}
printf("Degree of vertex %c: %d\n", 'A' + i, deg);
}
return 0;
}
Expected Output (C):
Adjacency Matrix:
0 1 1 0
1 0 0 1
1 0 0 1
0 1 1 0
Degree of vertex A: 2
Degree of vertex B: 2
Degree of vertex C: 2
Degree of vertex D: 2
5. Python Implementation: Graph (Adjacency List)
class Graph:
def __init__(self, directed=False):
self.directed = directed
self.adj = {}
def add_vertex(self, v):
if v not in self.adj:
self.adj[v] = []
def add_edge(self, u, v):
self.add_vertex(u)
self.add_vertex(v)
self.adj[u].append(v)
if not self.directed:
self.adj[v].append(u)
def display(self):
for vertex, neighbors in self.adj.items():
print(f"{vertex}: {neighbors}")
if __name__ == "__main__":
g = Graph(directed=False)
edges = [("A", "B"), ("A", "C"), ("B", "D"), ("C", "D")]
for u, v in edges:
g.add_edge(u, v)
print("Adjacency List Representation:")
g.display()
Expected Output (Python):
Adjacency List Representation:
A: ['B', 'C']
B: ['A', 'D']
C: ['A', 'D']
D: ['B', 'C']
