CMP 208 Lecture 3 Graph

You might also like

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 16

CMP 208 – Discrete Computing – Usmanu Danfodiyo University, Sokoto

Graph theory
Graph Theory is a branch of mathematics that is concerned with the study of relationships
between different objects. A graph consists of a finite set V and a set E of two-element
subsets of V. The elements of V are called vertices and the elements of E are called edges.
G = (V, E)
For instance, very formally we can introduce a graph like this: V = {1, 2, 3, 4}, E = {{1, 2}, {3,
4}, {2, 3}, {2, 4}}. In practice we more often think of a drawing like this:

Graph Data Structure


A Graph is a non-linear data structure consisting of vertices and edges. The vertices are
sometimes also referred to as nodes and the edges are lines or arcs that connect any two
nodes in the graph. More formally a Graph is composed of a set of vertices (V) and a set of
edges(E). The graph is denoted by G(V, E).
Basically, a graph is a data structure that is defined by two components:
1. A node or a vertex.
2. An edge E or ordered pair is a connection between two nodes u,v that is identified
by unique pair(u,v). The pair (u,v) is ordered because (u,v) is not same as (v,u) in case
of directed graph. The edge may have a weight or is set to one in case of unweighted
graph.
Consider the given below graph,

There are 6 nodes {A, B, C, D, E, F} and 8 edges ({B,C},{CD},{D,E},{E,F},{F,A},{A,B},{A,C},{E,C}) in


this graph.
Types of Graphs
1. Undirected Graphs: A graph in which edges have no direction, i.e., the edges do
not have arrows indicating the direction of traversal. Example: A social network
graph where friendships are not directional.

[Type here]
CMP 208 – Discrete Computing – Usmanu Danfodiyo University, Sokoto

2. Directed Graphs: A graph in which edges have a direction, i.e., the edges have
arrows indicating the direction of traversal. Example: A web page graph where
links between pages are directional.

3. Weighted Graphs: A graph in which edges have weights or costs associated


with them. Example: A road network graph where the weights can represent
the distance between two cities.

4. Unweighted Graphs: A graph in which edges have no weights or costs


associated with them. Example: A social network graph where the edges
represent friendships.

[Type here]
CMP 208 – Discrete Computing – Usmanu Danfodiyo University, Sokoto

5. Complete Graphs: A graph in which each vertex is connected to every other


vertex. Example: A tournament graph where every player plays against every
other player.
6. Bipartite Graphs: A graph in which the vertices can be divided into two disjoint
sets such that every edge connects a vertex in one set to a vertex in the other
set. Example: A job applicant graph where the vertices can be divided into job
applicants and job openings.
7. Trees: A connected graph with no cycles. Example: A family tree where each
person is connected to their parents.

8. Complete Graph:
A complete graph is an undirected graph in which every pair of distinct vertices is
connected by a unique edge. In other words, every vertex in a complete graph is
adjacent to all other vertices. A complete graph is denoted by the symbol K_n, where
n is the number of vertices in the graph. In other words, a simple graph with n
vertices is called a complete graph if the degree of each vertex is n-1, that is, one
vertex is attached with n-1 edges or the rest of the vertices in the graph. A complete
graph is also called Full Graph.

[Type here]
CMP 208 – Discrete Computing – Usmanu Danfodiyo University, Sokoto

9. Cycles: A graph with at least one cycle. In other words, some number of vertices
connected in a closed chain Example: A bike-sharing graph where the cycles
represent the routes that the bikes take.

10. Subgraph:
A graph G1 = (V1, E1) is called a subgraph of a graph G (V, E) if V1(G) is a subset of
V(G) and E1(G) is a subset of E(G) such that each edge of G1 has same end vertices
as in G.

11. Connected or Disconnected Graph:


Graph G is said to be connected if any pair of vertices (Vi, Vj) of a graph G is
reachable from one another. Or a graph is said to be connected if there exists at least
one path between each pair of vertices in graph G, otherwise, it is disconnected. A
null graph with n vertices is a disconnected graph consisting of n components. Each
component consists of one vertex and no edge.

[Type here]
CMP 208 – Discrete Computing – Usmanu Danfodiyo University, Sokoto

12. Cyclic Graph:


A graph G consisting of n vertices and n> = 3 that is V1, V2, V3- – – – Vn and edges
(V1, V2), (V2, V3), (V3, V4)- – – – (Vn, V1) are called cyclic graph.

Advantages of graphs:
1. Graphs can be used to model and analyze complex systems and relationships.
2. They are useful for visualizing and understanding data.
3. Graph algorithms are widely used in computer science and other fields, such as social
network analysis, logistics, and transportation.
4. Graphs can be used to represent a wide range of data types, including social
networks, road networks, and the internet.
Disadvantages of graphs:
1. Large graphs can be difficult to visualize and analyze.
2. Graph algorithms can be computationally expensive, especially for large graphs.
3. The interpretation of graph results can be subjective and may require domain-
specific knowledge.
4. Graphs can be susceptible to noise and outliers, which can impact the accuracy of
analysis results.

[Type here]
CMP 208 – Discrete Computing – Usmanu Danfodiyo University, Sokoto

A Tree
A tree is a special type of graph that is connected and acyclic, meaning that there are no
cycles in the graph.
In a tree, there is a unique path between any two vertices, and there is a single vertex
called the root that is used as the starting point for traversing the tree. The concept of a
tree can be represented by the following.

From the above tree, every circle is called a node. 2 is the root node. 2, 5, 11, 4 are the leaf
nodes.
Trees can be used to model hierarchical relationships, such as the structure of a file
system or the organization of a company.
Trees can be binary or non-binary. In a binary tree, each node has at most two children,
while in a non-binary tree, each node can have any number of children.

Tree Data Structure


A tree is a kind of data structure that is used to represent the data in hierarchical form. It can
be defined as a collection of objects or entities called as nodes that are linked together to
simulate a hierarchy. Tree is a non-linear data structure as the data in a tree is not stored
linearly or sequentially.
Binary Search Tree

A binary search tree follows some order to arrange the elements. In a Binary search tree,
the value of left node must be smaller than the parent node, and the value of right node
must be greater than the parent node. This rule is applied recursively to the left and right
subtrees of the root.

Let's understand the concept of Binary search tree with an example.

[Type here]
CMP 208 – Discrete Computing – Usmanu Danfodiyo University, Sokoto

From the above Binary Search Tree, In the above figure, we can observe that the root node
is 40, and ALL the nodes of the left subtree are smaller than the root node (40), and all the
nodes of the right subtree are greater than the root node.

Similarly, we can see the left child of root node (30) is greater than its left child (25) and
smaller than its right child (35). So, it also satisfies the property of binary search tree.
Therefore, we can say that the tree in the above image is a binary search tree.

Suppose if we change the value of node 35 to 55 in the above tree, check whether the tree
will be binary search tree or not.

The value of root node is 40, which is greater than its left child 30 but smaller than right
child of 30, i.e., 55. So, the above tree does not satisfy the property of Binary search tree.
Therefore, the above tree is not a binary search tree.

[Type here]
CMP 208 – Discrete Computing – Usmanu Danfodiyo University, Sokoto

CONSTRUCTION OF BINARY SEARCH TREE


We first construct the root. The first element of preorder traversal is always the root. Then
we find the index of the first element which is greater than the root.
Let the index be ‘i’. The values between root and ‘i’ will be part of the left subtree, and the
values between ‘i'(inclusive) and ‘n-1’ will be part of the right subtree. Divide the given pre []
at index “i” and recur for left and right sub-trees.
For example: Let us build a binary search tree using the following.
{10, 5, 1, 7, 40, 50}.

10 is the first element, so we make it root. Now we look for the first element greater than
10, we find 40.
The values between root (10) and ‘i’ (40) – which are (5,1,7) - will be part of the left subtree.
the values between ‘i'(inclusive) (40) and ‘n-1’ - which are (40, 50) will be part of the right
subtree.
So, we know the structure of BST is as follows.:
10
/ \
{5, 1, 7} {40, 50}

We recursively follow the above steps for subarrays {5, 1, 7} and {40, 50}, and get the
complete tree.

Example 2: Now, let's see the creation of binary search tree using an example.

Suppose the data elements are - 45, 15, 79, 90, 10, 55, 12, 20, 50

45

(15, 10, 12, 20) (79, 90,55,50)

15 79

(10,12)(20) (55,50) (90)

10 20 55 90

()(12) (50)()

[Type here]
CMP 208 – Discrete Computing – Usmanu Danfodiyo University, Sokoto

o First, we insert 45 into the tree as the root of the tree.


o Then, read the next element; if it is smaller than the root node, insert it as the root of
the left subtree, and move to the next element.
o Otherwise, if the element is larger than the root node, then insert it as the root of
the right subtree.

#
Searching In Binary Search Tree

Searching means to find or locate a specific element or node in a data structure. In Binary
search tree, searching a node is easy because elements in BST are stored in a specific order.
The steps of searching a node in Binary Search tree are listed as follows -

1. First, compare the element to be searched with the root element of the tree.
2. If root is matched with the target element, then return the node's location.
3. If it is not matched, then check whether the item is less than the root element, if it is
smaller than the root element, then move to the left subtree.
4. If it is larger than the root element, then move to the right subtree.
5. Repeat the above procedure recursively until the match is found.
6. If the element is not found or not present in the tree, then return NULL.

Now, let's understand the searching in binary tree using an example. We are taking the
binary search tree formed above. Suppose we have to find node 20 from the below tree

[Type here]
CMP 208 – Discrete Computing – Usmanu Danfodiyo University, Sokoto

Step I:

80
Step II

Step II

[Type here]
CMP 208 – Discrete Computing – Usmanu Danfodiyo University, Sokoto

Loosey–goosey graphs
When we first started looking at non-linear structures, we learned about their most
fundamental characteristic: that their data doesn’t follow an order — at least, not an obvious
numerical one, like we see in arrays or linked lists. Trees, as we learned, start with a root
node, and might connect to other nodes, which means that could contain subtrees within
them. Trees are defined by a certain set of rules: one root node may or may not connect to
others, but ultimately, it all stems from one specific place. Some trees have
even more specific rules, like binary search trees, which can only ever have two links
to two nodes at any given time.
But what if we did something kind of crazy and just…threw these rules out the window?
Well, as it turns out, we totally can do that! It’s just that we wouldn’t be dealing with trees
anymore — we’d be dealing with something called a graph.
Trees are nothing more than restricted types of graphs, just with many more rules to follow. A
tree will always be a graph, but not all graphs will be trees.

Graphs with direction, and graphs without


Okay, so we know that graphs pretty much break all the rules that we know. However, there
is one characteristic that every graph must have: every graph always needs to have, at the
very least, one single node. Just as how trees need at least one root node to be considered a
“tree”, similarly, a graph needs at least a single node order to be considered a “graph”. A
graph with just one node is usually referred to as a singleton graph, although we won’t
really be dealing with those.
Most of the graphs we’ll be dealing with are a bit more complex. But don’t be worried — we
won’t be diving into the super complicated graphs today. And trust me, some graphs really
are complicated!

[Type here]
CMP 208 – Discrete Computing – Usmanu Danfodiyo University, Sokoto

Graph Transversal
A graph traversal is the process of systematically visiting each node in a graph. This can be
tricky because many graphs have cycles (loops), which means that, unless you keep a good
record of the routes you take, you can end up going round in circles! There are two main
approaches: breadth-first and depth-first.
BREADTH-FIRST
A breadth-first search (BFS) is commonly used to find the path containing the least number
of nodes between two points in an unweighted graph. This is not the same as the classic
shortest path problem because it refers to the number of nodes, not the sum of the weights
between the nodes.
The algorithm starts searching at a designated start node and searches through all the
adjacent nodes (neighbours) before moving on. You can think of this process as moving out
in waves from a given point. Another simple way to visualise a breadth-first search algorithm
is to imagine that you are making a cake one layer at a time. You can't add the next layer
unless the previous one is complete.
This process uses a queue as a supporting data structure to keep track of the nodes that
have not been fully explored. As each node is discovered, it is added to the queue.

Breadth First Search (BFS) for a Graph

The Breadth First Search (BFS) algorithm is used to search a graph data structure for a
node that meets a set of criteria. It starts at the root of the graph and visits all nodes at
the current depth level before moving on to the nodes at the next depth level.

A Boolean visited array is used to mark the visited vertices. For simplicity, it is assumed
that all vertices are reachable from the starting vertex. BFS uses a queue data structure for
traversal.

Illustration of How does BFS work


Let us understand the working of the algorithm with the help of the following example.
Step1: Initially queue and visited arrays are empty.

[Type here]
CMP 208 – Discrete Computing – Usmanu Danfodiyo University, Sokoto

Step2: Push node 0 into queue and mark it visited.

Step 3: Remove node 0 from the front of queue and visit the unvisited neighbours and
push them into queue.

Step 4: Remove node 1 from the front of queue and visit the unvisited neighbours and
push them into queue.

Step 5: Remove node 2 from the front of queue and visit the unvisited neighbours and
push them into queue.

[Type here]
CMP 208 – Discrete Computing – Usmanu Danfodiyo University, Sokoto

Step 6: Remove node 3 from the front of queue and visit the unvisited neighbours and
push them into queue.
As we can see that every neighbour of node 3 is visited, so move to the next node that are
in the front of the queue.

Steps 7: Remove node 4 from the front of queue and visit the unvisited neighbours and
push them into queue.
As we can see that every neighbour of node 4 are visited, so move to the next node that is
in the front of the queue.

How Depth First Search (DFS) work


Depth-first search is an algorithm for traversing or searching tree or graph data structures.
The algorithm starts at the root node (selecting some arbitrary node as the root node in
the case of a graph) and explores as far as possible along each branch before
backtracking.
Let us understand the working of Depth First Search with the help of the following
illustration:

Step1: Initially stack and visited arrays are empty.

[Type here]
CMP 208 – Discrete Computing – Usmanu Danfodiyo University, Sokoto

Step 2: Visit 0 and put its adjacent nodes which are not visited yet into the stack.

Step 3: Now, Node 1 at the top of the stack, so visit node 1 and pop it from the stack and
put all its adjacent nodes which are not visited in the stack.

Step 4: Now, Node 2 at the top of the stack, so visit node 2 and pop it from the stack and
put all its adjacent nodes which are not visited (i.e, 3, 4) in the stack.

Step 5: Now, Node 4 at the top of the stack, so visit node 4 and pop it from the stack and
put all of its adjacent nodes which are not visited in the stack.

[Type here]
CMP 208 – Discrete Computing – Usmanu Danfodiyo University, Sokoto

Step 6: Now, Node 3 at the top of the stack, so visit node 3 and pop it from the stack and
put all of its adjacent nodes which are not visited in the stack.

Choice of DFS vs BFS


BFS and DFS have distinct properties and behaviours, depending on the structure and size of
the graph.
1. BFS is more suitable for finding the shortest path or the closest node to the starting
node, while DFS is more suitable for finding the longest path or the farthest node
from the starting node.
2. BFS is more memory intensive than DFS, as it needs to store all the nodes at each
level, while DFS only needs to store the current path.
3. BFS is more likely to find a solution faster than DFS, if there is one, as it explores all
possible paths at each level, while DFS may get stuck in a dead end or a cycle.
4. BFS is more predictable than DFS, as it always visits the nodes in the same order,
while DFS may vary depending on the order of the edges.

Python Codes: The codes can be found in the link below.


https://colab.research.google.com/drive/1i3aLbOeYSsVheknR3SpSd2U9vtwdSzCW?
usp=sharing

Applications of Graph
Graph is a data structure which is used extensively in our real-life.
1. Social Network: Each user is represented as a node and all their activities, suggestion
and friend list are represented as an edge between the nodes.
2. Google Maps: Various locations are represented as vertices or nodes and the roads
are represented as edges and graph theory is used to find shortest path between two
nodes.
3. Recommendations on e-commerce websites: The “Recommendations for you”
section on various e-commerce websites uses graph theory to recommend items of
similar type to user’s choice.
4. Graph theory is also used to study molecules in chemistry and physics.

[Type here]

You might also like