0% found this document useful (0 votes)
10 views

graph

A graph is a data structure consisting of vertices and edges, used to represent various real-life applications such as networks and social media. Common representations of graphs include adjacency matrices and adjacency lists, each with their own advantages and disadvantages regarding space and efficiency. The document also covers graph terminology, types of graphs, and basic operations for manipulating graphs.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

graph

A graph is a data structure consisting of vertices and edges, used to represent various real-life applications such as networks and social media. Common representations of graphs include adjacency matrices and adjacency lists, each with their own advantages and disadvantages regarding space and efficiency. The document also covers graph terminology, types of graphs, and basic operations for manipulating graphs.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 12

Graph and its representations

A graph is a data structure that consists of the following two components:


1. A finite set of vertices also called as nodes.
2. A finite set of ordered pair of the form (u, v) called as edge. The pair is
ordered because (u, v) is not the same as (v, u) in case of a directed
graph(di-graph). The pair of the form (u, v) indicates that there is an edge
from vertex u to vertex v. The edges may contain weight/value/cost.
Graphs are used to represent many real-life applications: Graphs are used to
represent networks. The networks may include paths in a city or telephone
network or circuit network. Graphs are also used in social networks like
linkedIn, Facebook. For example, in Facebook, each person is represented
with a vertex(or node). Each node is a structure and contains information like
person id, name, gender, and locale. See this for more applications of
graph.
Following is an example of an undirected graph with 5 vertices.

The following two are the most commonly used representations of a graph.
1. Adjacency Matrix
2. Adjacency List
There are other representations also like, Incidence Matrix and Incidence
List. The choice of graph representation is situation-specific. It totally
depends on the type of operations to be performed and ease of use.
Adjacency Matrix:
Adjacency Matrix is a 2D array of size V x V where V is the number of
vertices in a graph. Let the 2D array be adj[][], a slot adj[i][j] = 1 indicates that
there is an edge from vertex i to vertex j. Adjacency matrix for undirected
graph is always symmetric. Adjacency Matrix is also used to represent
weighted graphs. If adj[i][j] = w, then there is an edge from vertex i to vertex j
with weight w.
The adjacency matrix for the above example graph is:

Pros: Representation is easier to implement and follow. Removing an edge


takes O(1) time. Queries like whether there is an edge from vertex ‘u’ to
vertex ‘v’ are efficient and can be done O(1).
Cons: Consumes more space O(V^2). Even if the graph is sparse(contains
less number of edges), it consumes the same space. Adding a vertex is
O(V^2) time. Computing all neighbors of a vertex takes O(V) time (Not
efficient).
Please see this for a sample Python implementation of adjacency matrix.

Adjacency List:
An array of lists is used. The size of the array is equal to the number of
vertices. Let the array be an array[]. An entry array[i] represents the list of
vertices adjacent to the ith vertex. This representation can also be used to
represent a weighted graph. The weights of edges can be represented as
lists of pairs. Following is the adjacency list representation of the above
graph.
Pros: Saves space O(|V|+|E|). In the worst case, there can be C(V, 2)
number of edges in a graph thus consuming O(V^2) space. Adding a vertex
is easier. Computing all neighbors of a vertex takes optimal time.
Cons: Queries like whether there is an edge from vertex u to vertex v are not
efficient and can be done O(V).
In Real-life problems, graphs are sparse(|E| <<|V| 2). That’s why adjacency
lists Data structure is commonly used for storing graphs. Adjacency matrix
will enforce (|V|2) bound on time complexity for such algorithms.

Whats Is A Graph In C++?


As stated above, a graph in C++ is a non-linear data structure defined as a collection of
vertices and edges.

Given above is an example graph G. Graph G is a set of vertices {A,B,C,D,E} and a set
of edges {(A,B),(B,C),(A,D),(D,E),(E,C),(B,E),(B,D)}.

Types of Graphs – Directed And Undirected Graph


A graph in which the edges do not have directions is called the Undirected graph. The
graph shown above is an undirected graph.

A graph in which the edges have directions associated with them is called a Directed
graph.
In the directed graph shown above, edges form an ordered pair wherein each edge
represents a specific path from one vertex to another vertex. The vertex from which the
path initiates is called “Initial Node” while the vertex into which the path terminates is
called the “Terminal Node”.
Thus in above graph, the set of vertices is {A, B, C, D, E} and the set of edges is {(A,B),
(A,D),(B,C),(B,E),(D,E)(E,C)}.

We will discuss the graph terminology or the common terms used in relation to the graph
below.

Graph Terminology

1. Vertex: Each node of the graph is called a vertex. In the above graph, A, B, C,
and D are the vertices of the graph.
2. Edge: The link or path between two vertices is called an edge. It connects two or
more vertices. The different edges in the above graph are AB, BC, AD, and DC.
3. Adjacent node: In a graph, if two nodes are connected by an edge then they are
called adjacent nodes or neighbors. In the above graph, vertices A and B are
connected by edge AB. Thus A and B are adjacent nodes.
4. Degree of the node: The number of edges that are connected to a particular
node is called the degree of the node. In the above graph, node A has a degree
2.
5. Path: The sequence of nodes that we need to follow when we have to travel from
one vertex to another in a graph is called the path. In our example graph, if we
need to go from node A to C, then the path would be A->B->C.
6. Closed path: If the initial node is the same as a terminal node, then that path is
termed as the closed path.
7. Simple path: A closed path in which all the other nodes are distinct is called a
simple path.
8. Cycle: A path in which there are no repeated edges or vertices and the first and
last vertices are the same is called a cycle. In the above graph, A->B->C->D->A
is a cycle.
9. Connected Graph: A connected graph is the one in which there is a path
between each of the vertices. This means that there is not a single vertex which
is isolated or without a connecting edge. The graph shown above is a connected
graph.
10. Complete Graph: A graph in which each node is connected to another is called
the Complete graph. If N is the total number of nodes in a graph then the
complete graph contains N(N-1)/2 number of edges.
11. Weighted graph: A positive value assigned to each edge indicating its length
(distance between the vertices connected by an edge) is called weight. The
graph containing weighted edges is called a weighted graph. The weight of an
edge e is denoted by w(e) and it indicates the cost of traversing an edge.
12. Diagraph: A digraph is a graph in which every edge is associated with a specific
direction and the traversal can be done in specified direction only.
Graph Representation
The way in which graph data structure is stored in memory is called “representation”.
The graph can be stored as a sequential representation or as a linked representation.

Both these types are described below.

Sequential Representation
In the sequential representation of graphs, we use the adjacency matrix. An adjacency
matrix is a matrix of size n x n where n is the number of vertices in the graph.

The rows and columns of the adjacency matrix represent the vertices in a graph. The
matrix element is set to 1 when there is an edge present between the vertices. If the
edge is not present then the element is set to 0.

Given below is an example graph that shows its adjacency matrix.


We have seen the adjacency matrix for the above graph. Note that since this is an
undirected graph, and we can say that the edge is present in both directions. For
Example, as edge AB is present, we can conclude that edge BA is also present.
In the adjacency matrix, we can see the interactions of the vertices which are matrix
elements that are set to 1 whenever the edge is present and to 0 when the edge is
absent.

Now let us see the adjacency matrix of a directed graph.

As shown above, the intersection element in the adjacency matrix will be 1 if and only if
there is an edge directed from one vertex to another.

In the above graph, we have two edges from vertex A. One edge terminates into vertex
B while the second one terminates into vertex C. Thus in adjacency matrix the
intersection of A & B is set to 1 as the intersection of A & C.

Next, we will see the sequential representation for the weighted graph.

Given below is the weighted graph and its corresponding adjacency matrix.

We can see that the sequential representation of a weighted graph is different from the
other types of graphs. Here, the non-zero values in the adjacency matrix are replaced by
the actual weight of the edge.
The edge AB has weight = 4, thus in the adjacency matrix, we set the intersection of A
and B to 4. Similarly, all the other non-zero values are changed to their respective
weights.

The adjacency list is easier to implement and follow. Traversal i.e. to check if there is an
edge from one vertex to another takes O(1) time and removing an edge also takes O(1).

Whether the graph is sparse (fewer edges) or dense, it always takes more amount of
space.

Linked Representation
We use the adjacency list for the linked representation of the graph. The adjacency list
representation maintains each node of the graph and a link to the nodes that are
adjacent to this node. When we traverse all the adjacent nodes, we set the next pointer
to null at the end of the list.

Let us first consider an undirected graph and its adjacency list.

As shown above, we have a linked list (adjacency list) for each node. From vertex A, we
have edges to vertices B, C and D. Thus these nodes are linked to node A in the
corresponding adjacency list.

Next, we construct an adjacency list for the directed graph.


In the above-directed graph, we see that there are no edges originating from vertex E.
Hence the adjacency list for vertex E is empty.

Now let us construct the adjacency list for the weighted graph.

For a weighted graph, we add an extra field in the adjacency list node to denote the
weight of the edge as shown above.

Adding vertex in the adjacency list is easier. It also saves space due to the linked list
implementation. When we need to find out if there is an edge between one vertex to
another, the operation is not efficient.

Basic Operations For Graphs


Following are the basic operations that we can perform on the graph data
structure:
 Add a vertex: Adds vertex to the graph.
 Add an edge: Adds an edge between the two vertices of a graph.
 Display the graph vertices: Display the vertices of a graph.
C++ Graph Implementation Using Adjacency List
Now we present a C++ implementation to demonstrate a simple graph using the
adjacency list.

Here we are going to display the adjacency list for a weighted directed graph. We have
used two structures to hold the adjacency list and edges of the graph. The adjacency list
is displayed as (start_vertex, end_vertex, weight).
Heap

Heap is a special case of balanced binary tree data structure where the root-
node key is compared with its children and arranged accordingly. If α has
child node β then −

key(α) ≥ key(β)

As the value of parent is greater than that of child, this property


generates Max Heap. Based on this criteria, a heap can be of two types –
For Input → 35 33 42 10 14 19 27 44 26 31
Min-Heap − Where the value of the root node is less than or equal to either
of its children.
Max-Heap − Where the value of the root node is greater than or equal to
either of its children.

Both trees are constructed using the same input and order of arrival.

Max Heap Construction Algorithm

We shall use the same example to demonstrate how a Max Heap is created.
The procedure to create Min Heap is similar but we go for min values instead
of max values.

We are going to derive an algorithm for max heap by inserting one element
at a time. At any point of time, heap must maintain its property. While
insertion, we also assume that we are inserting a node in an already
heapified tree.

Step 1 − Create a new node at the end of heap.


Step 2 − Assign new value to the node.
Step 3 − Compare the value of this child node with its parent.
Step 4 − If value of parent is less than child, then swap them.
Step 5 − Repeat step 3 & 4 until Heap property holds.
Note − In Min Heap construction algorithm, we expect the value of the
parent node to be less than that of the child node.

Let's understand Max Heap construction by an animated illustration. We


consider the same input sample that we used earlier.
Heap
elements: 44 42 35 33 31 19 27 10 26 14
Maximum element: 44

Max Heap Deletion Algorithm

Let us derive an algorithm to delete from max heap. Deletion in Max (or Min)
Heap always happens at the root to remove the Maximum (or minimum)
value.

Step 1 − Remove root node.


Step 2 − Move the last element of last level to root.
Step 3 − Compare the value of this child node with its parent.
Step 4 − If value of parent is less than child, then swap them.
Step 5 − Repeat step 3 & 4 until Heap property holds.

You might also like