0% found this document useful (0 votes)
12 views17 pages

Chapter 7 ALGO

Chapter Seven of the document covers Graph Data Structures, explaining their components such as vertices and edges, and their applications in various fields. It discusses different types of graphs, including directed and undirected graphs, and introduces graph representation methods like adjacency matrices and lists. Additionally, it outlines graph traversal techniques (BFS and DFS) and concepts related to minimum spanning trees, including algorithms like Kruskal's and Prim's.

Uploaded by

Seladdin Yassin
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)
12 views17 pages

Chapter 7 ALGO

Chapter Seven of the document covers Graph Data Structures, explaining their components such as vertices and edges, and their applications in various fields. It discusses different types of graphs, including directed and undirected graphs, and introduces graph representation methods like adjacency matrices and lists. Additionally, it outlines graph traversal techniques (BFS and DFS) and concepts related to minimum spanning trees, including algorithms like Kruskal's and Prim's.

Uploaded by

Seladdin Yassin
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/ 17

Data Structure and Algorithms For 2nd Year Computer Science Students

Chapter Seven
Graph Data structure
Graph is another nonlinear data structures. Graphs representations have found application in
almost all subjects like geography, engineering and solving games and puzzles.
A graph G consist of
1. Set of vertices V (called nodes), (V = {v1, v2, v3, v4......}) and
2. Set of edges E (i.e., E {e1, e2, e3......cm}
• Each vertex represents a city
• Each edge represents a direct flight between two cities
• A query on direct flights = a query on whether an edge exists
• A query on how to get to a location = does a path exist from A to B

We can even associate costs to edges (weighted graphs), then ask”what is the cheapest path from
A to B”
A graph can be represents as G = (V, E), where V is a finite and non empty set at vertices and E
is a set of pairs of vertices called edges. Each edge ‗e‘ in E is identified with a unique pair (a, b)
of nodes in V, denoted by e = [a, b].

A B

C D

Edge: let ‘G‘ be a graph, ‘V‘ is a finite set of vertices and ‘E‘ finite set of edges. Then an edge
can be defined, (V, W), if there is an incident line between the two vertices V, W.
As per the above example the set of vertices are
V= {A, B, C, D}; and the set of edges are
E= {(A, B), (A, C), (A, D), (B, D), (C, D)}
As per the example let us consider an edge (A, B), this can also be written as (B, A) because
there is no direction between A and B vertices.
Directed Graph
A directed graph G is defined as an ordered pair (V, E) where, V is a set of vertices and the
ordered pairs in E are called edges on V. A directed graph can be represented geometrically as a
set of marked points (called vertices) V with a set of arrows (called edges) E between pairs of
points (or vertex or nodes) so that there is at most one arrow from one vertex to another vertex.
Let G be the graph and ‘V‘ be a finite set of Vertices and ‘E‘ be finite set of edges. Then there
exist an edge (v, w) will not equal to (w, v) is known as directed graph.

1
Complied By Mr. Abraham W
Data Structure and Algorithms For 2nd Year Computer Science Students

As per above graph, V= {A, B, C, D} and E= {(A, C), (A, B), (B, D), (C, B), (D, C), (D, A).
Let us take an edge (A, C), this will not equal to (C, A).
Note: directed graph also called as digraph and undirected graph also known as graph.
An edge (a, b), in said to the incident with the vertices it joints, i.e., a, b. We can also say that the
edge (a, b) is incident from ‘a‘ to ‘b‘. The vertex ‘a‘ is called the initial vertex and the vertex b is
called the terminal vertex of the edge (a, b). If an edge that is incident from and into the same
vertex, say (b, b) of (e, e) in Fig below, is called a loop.

An undirected graph G is defined abstractly as an ordered pair (V, E), where V is a set of
vertices and the E is a set at edges. An undirected graph can be represented geometrically as a set
of marked points (called vertices) V with a set at lines (called edges) E between the points.
Two vertices are said to be adjacent if they are joined by an edge. Consider edge (a, b), the
vertex ‘a‘ is said to be adjacent to the vertex b, and the vertex b is said to be adjacent from the
vertex a. A vertex is said to be an isolated vertex if there is no edge incident with it. In Figure
above vertex e is an isolated vertex.
An undirected graph can be represented geometrically as a set of marked points (called vertices)
V with a set at lines (called edges) E between the points.
Degree: let G be the graph and let ‘V‘ be a finite set of vertices and let ‘E‘ be finite set of edges.
Then, degree can be defined as the number of incident edges upon the vertex.

2
Complied By Mr. Abraham W
Data Structure and Algorithms For 2nd Year Computer Science Students

Out degree : let ‘V’ be vertex then starting point of an edge from v to another vertex is known as
out degree.

Outdegree(A)=2
Outdegree(B)=1
Outdegree(C)=1
Outdegree(D)=2
Indegree : let ‘V’ be vertex and an edge reaches to vertex v from another vertex is known as in
degree.

Indegree (A)=1
Indegree (B)=2
Indegree (C)=2
Indegree (D)=1

Loop: a loop can be defined that starting and ending point of an edge will be the same.
Path: a path from vertex ‘V‘ to another vertex ‘W‘ is the sequence of vertices with several
adjacent vertices.

3
Complied By Mr. Abraham W
Data Structure and Algorithms For 2nd Year Computer Science Students

Graph Representation
Graph is a mathematical structure and finds its application is many areas, where the problem is to
be solved by computers. The problems related to graph G must be represented in computer
memory using any suitable data structure to solve the same.
There are two popular computer representations of a graph. Both represent the vertex set and the
edge set, but in different ways:
 Adjacency Matrix: Use a 2D matrix to represent the graph
 Adjacency List: Use a 1D array of linked lists

Adjacency Matrix:
2D array A[0..n-1, 0..n-1], where n is the number of vertices in the graph
* Each row and column is indexed by the vertex id
n e,g a=0, b=1, c=2, d=3, e=4
* A[i][j]=1 if there is an edge connecting vertices i and j; otherwise, A[i][j]=0
* The storage requirement is Θ(n2). It is not efficient if the graph has few edges. An adjacency
matrix is an appropriate representation if the graph is dense: |E|=Θ(|V|2)
* We can detect in O(1) time whether two vertices are connected.

4
Complied By Mr. Abraham W
Data Structure and Algorithms For 2nd Year Computer Science Students

Adjacency List: If the graph is not dense, in other words, sparse, a better solution is an adjacency
list
* The adjacency list is an array A[0..n-1] of lists, where n is the number of vertices in the graph.
* Each array entry is indexed by the vertex id
* Each list A[i] stores the ids of the vertices adjacent to vertex i

Storage of Adjacency List


* The array takes up Θ (n) space
* Define degree of v, deg (v), to be the number of edges incident to v. Then, the total space to
store the graph is proportional to:
∑ deg(v)
5
Complied By Mr. Abraham W
Data Structure and Algorithms For 2nd Year Computer Science Students

Vertex v
* An edge e= {u, v} of the graph contributes a count of 1 to deg (u) and contributes a count 1 to
deg (v)
* Therefore, Σvertex vdeg(v) = 2m, where m is the total number of edges
* In all, the adjacency list takes up Θ (n + m) space
If m = O (n2) (i.e. dense graphs), both adjacent matrix and adjacent lists use Θ (n2) space.
If m = O (n), adjacent list outperforms adjacent matrix
* However, one cannot tell in O (1) time whether two vertices are connected

Adjacency List vs. Matrix


* Adjacency List
More compact than adjacency matrices if graph has few edges
Requires more time to find if an edge exists
* Adjacency Matrix
Always require n2 space
This can waste a lot of space if the number of edges is sparse
Can quickly find if an edge exists
It‘s a matrix; some algorithms can be solved by matrix computation!

Traversing a Graph
Many application of graph requires a structured system to examine the vertices and edges of a
graph G. That is a graph traversal, which means visiting all the nodes of the graph. There are two
graph traversal methods.
(a) Breadth First Search (BFS)
(b) Depth First Search (DFS)

Breadth First Search


Given an input graph G = (V, E) and a source vertex S, from where the searching starts. The
breadth first search systematically traverses the edges of G to explore every vertex that is
reachable from S. Then we examine the entire vertices neighbor to source vertex S. Then we
traverse all the neighbors of the neighbors of source vertex S and so on. A queue is used to keep
track of the progress of traversing the neighbor nodes.
BFS can be further discussed with an example. Considering the graph G in figure below

6
Complied By Mr. Abraham W
Data Structure and Algorithms For 2nd Year Computer Science Students

The linked list (or adjacency list) representation of the graph figure above is also shown.
Suppose the source vertex is A. Then following steps will illustrate the BFS.
Step 1: Initially push A (the source vertex) to the queue.

Front=0 Front
Rear=0
A

Rear
Step 2: Pop (or remove) the front element A from the queue (by incrementing front = front +1)
and display it. Then push (or add) the neighboring vertices of A to the queue, (by incrementing
Rear = Rear +1) if it is not in queue.

Front=1 Front
Rear=2
A B C

Rear
Step3: pop the front element B from the queue and display it. Then add the neighboring vertices
to the queue, if it is not in queue.
Front=2 Front
Rear=4
A B C D E

Rear
One of the neighboring elements C of B is preset in the queue. So C is not added to queue.
Step4: Remove the front element C and display it. Add the neighboring vertices of C,if it is not
present in queue.
Front=3 Front
Rear=5
A B C D E F

Rear
One of the neighboring elements E of C is present in the queue. So E is not added.
Step5: Remove the front element D, and add the neighboring vertex if it is not present in queue.

7
Complied By Mr. Abraham W
Data Structure and Algorithms For 2nd Year Computer Science Students

8
Complied By Mr. Abraham W
Data Structure and Algorithms For 2nd Year Computer Science Students

Depth First Search


The depth first search (DFS), as its name suggest, is to search deeper in the graph, when ever
possible. Given an input graph G = (V, E) and a source vertex S, from where the searching starts.
First we visit the starting node. Then we travel through each node along a path, which begins at
S. That is we visit a neighbor vertex of S and again a neighbor of a neighbor of S, and so on. The
implementation of BFS is almost same except a stack is used instead of the queue. DFS can be
further discussed with an example. Consider the graph in the Figure above and its linked list
representation. Suppose the source vertex is I.
The following steps will illustrate the DFS
Step 1: Initially push I on to the stack.
STACK: I
DISPLAY:
Step 2: Pop and display the top element, and then push all the neighbors of popped element (i.e.,
I) onto the stack, if it is not visited (or displayed or not in the stack.
STACK: G, H
DISPLAY: I
Step 3: Pop and display the top element and then push all the neighbors of popped the element
(i.e., H) onto top of the stack, if it is not visited.
STACK: G, E
DISPLAY: I, H

9
Complied By Mr. Abraham W
Data Structure and Algorithms For 2nd Year Computer Science Students

The popped element H has two neighbors E and G. G is already visited, means G is either in the
stack or displayed. Here G is in the stack. So only E is pushed onto the top of the stack.
Step 4: Pop and display the top element of the stack. Push all the neighbors of the popped
element on to the stack, if it is not visited.
STACK: G, D, F
DISPLAY: I, H, E
Step 5: Pop and display the top element of the stack. Push all the neighbors of the popped
element onto the stack, if it is not visited.
STACK: G, D

DISPLAY: I, H, E, F
The popped element (or vertex) F has neighbor(s) H, which is already visited. Then H is
displayed, and will not be pushed again on to the stack.
Step 6: The process is repeated as follows.
STACK: G
DISPLAY: I, H, E, F, D
STACK: //now the stack is empty
DISPLAY: I, H, E, F, D, G
So I, H, E, F, D, G is the DFS traversal of graph Fig 9:20 from the source vertex I.
Algorithm
1. Input the vertices and edges of the graph G = (V, E).
2. Input the source vertex and assign it to the variable S.
3. Push the source vertex to the stack.
4. Repeat the steps 5 and 6 until the stack is empty.
5. Pop the top element of the stack and display it.
6. Push the vertices which is neighbor to just popped element, if it is not in the queue and
displayed (ie; not visited).
7. Exit.

Minimum Spanning Tree


A minimum spanning tree (MST) for a graph G = (V, E) is a sub graph G1 = (V1, E1) of
G contains all the vertices of G.
1. The vertex set V1 is same as that at graph G.
2. The edge set E1 is a subset of G.
3. And there is no cycle.
If a graph G is not a connected graph, then it cannot have any spanning tree. In this case, it will
have a spanning forest. Suppose a graph G with n vertices then the MST will have (n – 1) edges,
assuming that the graph is connected.

10
Complied By Mr. Abraham W
Data Structure and Algorithms For 2nd Year Computer Science Students

A minimum spanning tree (MST) for a weighted graph is a spanning tree with minimum weight.
That is all the vertices in the weighted graph will be connected with minimum edge with
minimum weights. Figure below shows the minimum spanning tree of the weighted graph in
Figure above.

Two different famous algorithms can be used to obtain a minimum spanning tree of a connected
weighted and undirected graph.
1. Kruskal‘s Algorithm
2. Prim‘s Algorithm

Kruskal’s Algorithm
This is a one of the popular algorithm and was developed by Joseph Kruskal. To create a
minimum cost spanning trees, using Kruskalls, we begin by choosing the edge with the minimum
cost (if there are several edges with the same minimum cost, select any one of them) and add it to
the spanning tree. In the next step, select the edge with next lowest cost, and so on, until we have
selected (n – 1) edges to form the complete spanning tree. The only thing of which beware is that
we don‘t form any cycles as we add edges to the spanning tree. Let us discuss this with an
example. Consider a graph G in Figure below to generate the minimum spanning tree.

11
Complied By Mr. Abraham W
Data Structure and Algorithms For 2nd Year Computer Science Students

The minimum cost edge in the graph G in Figure above is 1. If you analyze closely there are two
edges (i.e., (7, 3), (4, 9)) with the minimum cost 1. As the algorithm says select any one of them.
Here we select the edge (7, 3). Again we select minimum cost edge (i.e., 1), which is (4, 9).
Next we select minimum cost edge (i.e., 2). If you analyze closely there are two edges (i.e., (1,
2), (2, 3), (3, 6)) with the minimum cost 2. As the algorithm says select any one of them. Here
we select the edge (1, 2. Again we select minimum cost edge (i.e., 2), which is (2, 3). Next we
select minimum cost edge (i.e., 2), which is (3, 6).
Next minimum cost edge is (1, 9) with cost 3. Add the minimum cost edge to the minimum
spanning tree as shown in Figure below. If we analyze, next minimum cost edge is (1, 5) with
cost 4. Add the minimum cost edge to the minimum spanning tree.
Next minimum cost edge is (4, 8) with cost 5. Add the minimum cost edge to the minimum
spanning tree.

Above figures shows different stages of Kruskasl‘s Algorithm.


ALGORITHM
Suppose G = (V, E) is a graph, and T is a minimum spanning tree of graph G.
1. Initialize the spanning tree T to contain all the vertices in the graph G but no edges.
2. Choose the edge e with lowest weight from graph G.
3. Check if both vertices from e are within the same set in the tree T, for all such sets of
T. If it is not present, add the edge e to the tree T, and replace the two sets that this edge
connects.
4. Delete the edge e from the graph G and repeat the step 2 and 3 until there is no more
edge to add or until the panning tree T contains (n-1) vertices.
5. Exit

12
Complied By Mr. Abraham W
Data Structure and Algorithms For 2nd Year Computer Science Students

Jarnik- Prim’s Algorithm

Consider all the edges adjacent to the vertices of the recently selected edge (here recently
selected edge is (4, 9)). And find the minimum cost edge that connects from recently selected
edge. Here it is (9, 1) as shown in Figure below.
Again consider all the edges adjacent to the vertices of the recently selected edge (here recently
selected edge is (9, 1)). And find the minimum cost edge that connects from recently selected
edge. Here it is (1, 2) as shown in Figure below.
Consider all the edges adjacent to the vertices of the recently selected edge (here recently
selected edge is (1, 2)). And find the minimum cost edge that connects from recently selected
edge. Here it is (2, 3) as shown in Figure below. And repeat the process of finding the minimum
cost edge that connects from recently selected edge.
Since all the vertices in the adjacent edges that can be reached from the recently selected edge
(i.e., (2, 3)) are visited, backtrack (or go back) to the path so as any other minimum cost adjacent
edges is there to connect the vertices which are not connected yet. Thus we find the adjacent
edge (3, 6) as shown in the Figure below.
Again since all the vertices in the adjacent edges that can be reached from the recently selected
edge (i.e., (3, 6)) are visited, backtrack (or go back) to the path so as any other minimum cost
adjacent edges is there to connect the vertices which are not connected yet. Thus we find the
adjacent edge (1, 5) as shown in the Figure below.
Next we find the minimum cost adjacent edges (4, 8) as shown in the Figure below.

Algorithm
Suppose G = (V, E) is a graph and T is a minimum spanning tree of graph G.
1. Initialize the spanning tree T to contain a vertex v1.
2. Choose an edge e = (v1, v2) of G such that v2 not equal to v1 and e has smallest weight among
the edges of G incident with v1.
3. Select an edge e = (v2, v3) of G such that v2 is not equal to v3 and e has smallest weight
among the edge of G incident with v2.
4. Suppose the edge e1, e2, e3 ... ei Then select an edge ei + 1 = (Vj, Vk) such that

13
Complied By Mr. Abraham W
Data Structure and Algorithms For 2nd Year Computer Science Students

(a) Vj ε{v1, v2, v3, ...... vi, vi + 1} and


(b) Vk ε {v1, v2, v3, ...... vi, vi + 1} such that ei+1 has smallest weight among the edge of G
5. Repeat the step 4 until (n – 1) edges have been chosen
6. Exit

Shortest Path
A path from a source vertex a to b is said to be shortest path if there is no other path from a to b
with lower weights. There are many instances, to find the shortest path for traveling from one
place to another. That is to find which route can reach as quickly as possible or a route for which
the traveling cost in minimum. Dijkstra's Algorithm is used find shortest path.

Algorithm
Set V = {V1, V2, V3 ...... Vn} contains the vertices and the edges E = {e1, e2, ...... em} of the
graph G. W(e) is the weight of an edge e, which contains the vertices V1 and V2. Q is a set of
vertices, which are not visited. m is the vertex in Q for which weight W(m) is minimum, i.e.,
minimum cost edge. S is a source vertex.
1. Input the source vertices and assign it to S
(a) Set W(s) = 0 and
(b) Set W (v) = ___ for all vertices V is not equal to S
2. Set Q = V which is a set of vertices in the graph
3. Suppose m be a vertices in Q for which W(m) is minimum
4. Make the vertices m as visited and delete it from the set Q
5. Find the vertices I which are incident with m and member of Q (That is the
vertices which are not visited)
6. Update the weight of vertices I = {i1, i2 ...... ik} by
(a) W(i1) = min [W(i1), W(m) + W(m, i1)]
7. If any changes is made in W(v), store the vertices to corresponding vertices i,
using the array, for tracing the shortest path
8. Repeat the process from step 3 to 7 until the set Q is empty
9. Exit
The above algorithm is illustrated with a graph in Figure below

14
Complied By Mr. Abraham W
Data Structure and Algorithms For 2nd Year Computer Science Students

15
Complied By Mr. Abraham W
Data Structure and Algorithms For 2nd Year Computer Science Students

If the source vertex is A and the destination vertex is D then the weight is 7 and the shortest path
can be traced from table at the right side as follows.
Start finding the shortest path from destination vertex to its shortest vertex. For example we want
to find the shortest path from A to D. Then find the shortest vertex from D, which is C. Check
the shortest vertex, is equal to source vertex. Otherwise assign the shortest vertex as new
destination vertex to find its shortest vertex as new destination vertex to find its shortest vertex.
This process continued until we reach to source vertex from destination vertex.
D→C
C→A
A, C, D is the shortest path

16
Complied By Mr. Abraham W
Data Structure and Algorithms For 2nd Year Computer Science Students

The efficiency of the Dijskras’s algorithm is analyzed by the iteration of the loop structures. The
while loop iteration n – 1 times to visit the minimum weighted edge. Potentially loop must be
repeated n times to examine every vertices in the graph. So the time complexity is O(n2).

17
Complied By Mr. Abraham W

You might also like