What is graph?
A graph is a mathematical structure consisting of two types of elements
• G = (V,E) where
– V is a set of nodes called vertices
——>The order of a graph is the number of its vertices, i.e. |V|
– E is a collection of edges that connect pairs of vertices
——-> The size of a graph is the number of its edges, i.e. |E|
Edge Types
Directed Edge: – Ordered pair of vertices (u,v) – First vertex u is the origin – Second vertex v is the destination EX: u -------> v
Undirected Edge:
– Unordered pair of vertices (u,v)
EX: u ——– v
A graph may be:
– Undirected, i.e. there is no distinction between two vertices associated with each edge
EX: edge (3,2) is the same as edge (2,3)
()Directed, i.e. the edges are directed from one vertex to the other
EX: edge (1,2) goes from node 1 to node 2,
1 –> 2
Edge components (information)
- They may have weights, costs, color associated with it
Weighted Undirected graph
EX: a network of airports
Weighted graph
It has weights associated with the edges. Numerical weights are sometimes referred to as cost
Why and when to use graphs over trees?
Endpoints (or end vertices) of an edge
Two or more edges having a vertex v as at least one of their endpoints are called edges incident to v
EX: (6, 10), (4,10)
Adjacent vertices
Two vertices connected by an edge are adjacent
Degree of a vertex
It is the number of edges starting or ending at that vertex
Degree in directed graphs
Out-degree: number of edges starting at that vertex
In-degree: number of edges ending at that vertex
A path
A sequence of edges (or of adjacent vertices)
The length of a path
The number of edges on that path
A simple path
A path where all its vertices and edges are distinct
A cycle
A path beginning and ending at the same vertex
A simple cycle
A cycle which does not pass through any vertex more than once
A loop
An edge whose endpoints are the same vertex
Labeled graph
Directed/Undirected graph
-All edges are directed/undirected
Regular graph
All vertices have the same degree
Data Structures for vertices
– Hash table (generally preferred)
– Array
– List
– Binary search tree
Data Structures for edges
– Adjacency list
– Adjacency Matrix
Adjacency list
Adjacency Matrix
It is a two dimensional array A of dimensions n×n (n is
the number of vertices in G) , where:
–If the graph is directed, then the element a(i,j) is 1 if and only if there is a directed edge from vertex i to vertex j.
– If the graph is undirected, then the element a(i, j) and a(j, i) are 1 if and only if there is an edge from vertex i to vertex j
a(i, j) = 1 if (i, j)∈E 0 if (i, j)∉E