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

UNIT 6 Tree and Graphs

Trees and graphs econpmics

Uploaded by

tamangdorje69
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views

UNIT 6 Tree and Graphs

Trees and graphs econpmics

Uploaded by

tamangdorje69
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 30

UNIT- 6

Tree and Graphs

Graphs Graph Theory


Introduction
Many situations that occur in computer science, physical science, communication science,
Economics and many others areas can be analyzed by using techniques found in a relatively
new area of mathematics called graph theory. Graphs can be used to represent almost any
problem involving discrete arrangements of objects where concern lies not with the internal
properties of these objects but with relationships among them
Graph is a discrete structure consisting of vertices and edges connecting the vertices. A graph G
= (V,E) is a mathematical model consists of two non empty sets: V = {v1, v2, , v3……. vn} is
called set of vertices and E = {e1, e2, e3….en} of ordered or unordered pairs of distinct vertices
called edges. We usually write G = (V,E) and say V is the vertex and E is the edge set of G
Applications of Graph
Graphs are used to solve problems in many fields. Some of them are as follows:
• Graphs are used to model the geographic maps of cities in which each place in city can
be represented by the node and the road connecting such places are represents the edge
• Graphs are used to model the computer network in which each node is a machine and
link between them represent the edge
• They are used to analyze the electric circuits, project planning, genetics etc
• Any structured problem can be modeled by graphs. Then can help to solve typical
problems those connected with finding shortest path of most economical route between
two vertices, or the smallest set of edges which connect all the vertices in a graph
• Graphs are used to study the structure of WWW
• It is used to find the number of different combination of flight between two cities in an
airline network
• It can be used to distinguish between two chemical compounds with the same molecular
formula but different structure
• It is also used to assign channels to television stations

6.1 Definition
- A graph G = (V, E) consists of V, a nonempty set of vertices (or nodes) and E, a set of edges.
- Each edge has either one or two vertices associated with it, called its endpoints.
- An edge is said to connect its endpoints.
- The set of vertices V of a graph G may be infinite.
- A graph with an infinite vertex set or an infinite number of edges is called an infinite graph,
and in comparison, a graph with a finite vertex set and a finite edge set is called a finite
graph.
EXAMPLE:

1
In the above graph,
V = {a, b, c, d, e}
E = {(a, b), (a, c), (b, d), (c, d), (d, e)}

Types of Graphs
Simple Graphs
- A graph in which each edge connects two different vertices and where no two edges
connect the same pair of vertices is called a simple graph.

Multigraphs
- Graphs that may have multiple edges connecting the same vertices are called multigraphs.

2
Pseudographs
- The edges that connect a vertex to itself, such edges are called loops.
- Graphs that may include loops, and possibly multiple edges connecting the same pair of
vertices or a vertex to itself, are sometimes called pseudographs.

Directed Graphs
- A directed graph (or digraph) (V, E) consists of a nonempty set of vertices V and a set of
directed edges (or arcs) E.
- Each directed edge is associated with an ordered pair of vertices.
- The directed edge associated with the ordered pair (u, v) is said to start at u and end at v.

Simple Directed Graph


- When a directed graph has no loops and has no multiple directed edges, it is called a
simple directed graph.

3
Directed Multigraph
- Directed graphs that may have multiple directed edges from a vertex to a second (possibly
the same) vertex are called directed multigraphs.
- When there are m directed edges, each associated to an ordered pair of vertices (u, v),
we say that (u, v) is an edge of multiplicity m.

Mixed Graph
- A graph with both directed and undirected edges is called a mixed graph.

Graph Models
Graphs are used in a wide variety of models.
➢ Social Networks
➢ Communication Networks
➢ Information Networks
➢ Software Design Applications
➢ Transportation Network
➢ Biological Networks and
➢ Tournaments

Graph Terminologies
Adjacent Vertices and Incident Edges
- Two vertices u and v in an undirected graph G are called adjacent (or neighbours) in G if
u and v are endpoints of an edge e of G.
- Such an edge e is called incident with the vertices u and v and e is said to connect u and v.

Neighbourhood Vertices
- The set of all neighbours of a vertex v of G = (V, E), denoted by N (v), is called
the neighbourhood of v.
- If A is a subset of V, we denote by N (A) the set of all vertices in G that are adjacent to at
least one vertex in A.
- So, 𝑁 (𝐴) = ⋃𝑣∈𝐴 𝑁 (𝑣).

Degree of a Vertix
- The degree of a vertex in an undirected graph is the number of edges incident with it,
except that a loop at a vertex contributes twice to the degree of that vertex.
- The degree of the vertex v is denoted by deg(v).
EXAMPLE: What are the degrees and what are the neighbourhoods of the vertices in the
graphs G and H displayed in figure below.

4
Fig: The Undirected Graphs G and H.
Solution:
- In G, deg(a) = 2, deg(b) = deg(c) = deg(f ) = 4, deg(d ) = 1, deg(e) = 3, and deg(g) = 0.
- The neighbourhoods of these vertices are N (a) = {b, f }, N (b) = {a, c, e, f }, N (c) = {b,
d, e,f }, N (d) = {c}, N (e) = {b, c, f }, N (f ) = {a, b, c, e}, and N (g) = ∅.
- In H, deg(a) = 4, deg(b) = deg(e) = 6, deg(c) = 1, and deg(d ) = 5.
- The neighbourhoods of these vertices are N (a) = {b, d, e}, N (b) = {a, b, c, d, e}, N (c) =
{b},N (d) = {a, b, e}, and N (e) = {a, b, d}.
Isolated and Pendant Vertices
- A vertex of degree zero is called isolated.
- It follows that an isolated vertex is not adjacent to any vertex.
- Vertex g in graph G in Example above is isolated.
- A vertex is pendant if and only if it has degree one.
- Consequently, a pendant vertex is adjacent to exactly one other vertex.
- Vertex d in graph G in Example above is pendant.

In-degree and Out-degree


- In a graph with directed edges the in-degree of a vertex v, denoted by deg−(v), is the
number of edges with v as their terminal vertex.
- The out-degree of v, denoted by deg+(v), is the number of edges with v as their initial
vertex.
- (Note that a loop at a vertex contributes 1 to both the in-degree and the out-degree of
this vertex.)
EXAMPLE: Find the in-degree and out-degree of each vertex in the graph G with directed
edges shown in Figure below.

5
Fig: The Directed Graph G.
Solution:
- The in-degrees in G are deg−(a) = 2, deg−(b) = 2, deg−(c) = 3, deg−(d) = 2, deg−(e) = 3,
and deg−(f ) = 0.
- The out-degrees are deg+(a) = 4, deg+(b) = 1, deg+(c) = 2, deg+(d) = 2, deg+(e) = 3,
and deg+(f ) = 0.

Underlying undirected graph


- The undirected graph that results from ignoring directions of edges is called the
underlying undirected graph.

Some Special Simple Graphs


Complete Graphs
- A complete graph on n vertices, denoted by Kn, is a simple graph that contains exactly one
edge between each pair of distinct vertices.
- The graphs Kn, for n = 1, 2, 3, 4, and 5 are displayed in Figure below.
- A simple graph for which there is at least one pair of distinct vertex not connected by an
edge is called non-complete.

Fig: The Graphs Kn for 1 ≤ n ≤ 5.

Cycles
- A cycle Cn, n ≥ 3, consists of n vertices v1, v2,..., vn and edges {v1, v2}, {v2, v3},...,{vn−1,
vn}, and {vn, v1}.

6
Fig: The Cycles C3, C4, C5, and C6.

Wheels
We obtain a wheel Wn when we add an additional vertex to a cycle Cn, for n ≥ 3, and connect
this new vertex to each of the n vertices in Cn, by new edges.

Fig: The Wheels W3, W4, W5, and


W6.

n-Cubes
- An n-dimensional hypercube, or n-cube, denoted by Qn, is a graph that has vertices
representing the 2n bit strings of length n.
- Two vertices are adjacent if and only if the bit strings that they represent differ in exactly
one bit position.

Fig: The n-cube Qn, n = 1, 2, 3

Bipartite Graphs
- A simple graph G is called bipartite if its vertex set V can be partitioned into two disjoint
sets V1 and V2 such that every edge in the graph connects a vertex in V1 and a vertex in V2
(so that no edge in G connects either two vertices in V1 or two vertices in V2).
- When this condition holds, we call the pair (V1, V2) a bipartition of the vertex set V of G.

EXAMPLE: Is the graph displayed in figure bipartite?

7
Solution:
- Graph G is bipartite because its vertex set is the union of two disjoint sets, {a, b, d} and {c,
e, f, g}, and each edge connects a vertex in one of these subsets to a vertex in the other
subset.

Complete Bipartite Graphs


- A complete bipartite graph Km,n is a graph that has its vertex set partitioned into two
subsets of m and n vertices, respectively with an edge between two vertices if and only if
one vertex is in the first subset and the other vertex is in the second subset.
EXAMPLE:

Subgraph
- A subgraph of a graph G = (V, E) is a graph H = (W, F), where W ⊆ V and F ⊆ E. A
subgraphH of G is a proper subgraph of G if H = G.
- Let G = (V, E) be a simple graph. The subgraph induced by a subset W of the vertex set V
is the graph (W, F), where the edge set F contains an edge in E if and only if both endpoints
of this edge are in W.
- The union of two simple graphs G1 = (V1, E1) and G2 = (V2, E2) is the simple graph
with vertex set V1 𝖴 V2 and edge set E1 𝖴 E2. The union of G1 and G2 is denoted by G1
𝖴 G2.

Representing Graphs
Adjacency lists
- Specify the vertices that are adjacent to each vertex of the graph.

8
EXAMPLE:

Adjacency Matrices
- The adjacency matrix A (or AG) of G, with respect to this listing of the vertices, is the n x
n zero–one matrix with 1 as its (i, j)th entry when vi and vj are adjacent, and 0 as its (i, j)th
entry when they are not adjacent.
- In other words, if its adjacency matrix is A = [aij], then

EXAMPLE: Draw a graph with the adjacency matrix

Incidence Matrices
- Another common way to represent graphs is to use incidence matrices.
- Let G = (V, E) be an undirected graph.
- Suppose that v1, v2,..., vn are the vertices and e1, e2,...,em are the edges of G.
- Then the incidence matrix with respect to this ordering of V and E is the n × m matrix M =
[mij], where

EXAMPLE: Represent the graph shown in figure below with an incidence matrix.
Solution: The incidence matrix is

9
Isomorphism of Graphs
- The simple graphs G1 = (V1, E1) and G2 = (V2, E2) are isomorphic if there exists a one-
to- one and onto function f from V1 to V2 with the property that a and b are adjacent in
G1 if and only if f(a) and f(b) are adjacent in G2, for all a and b in V1.
- Such a function f is called an isomorphism.
- Two simple graphs that are not isomorphic are called nonisomorphic.
EXAMPLE: Show that the graphs G = (V, E) and H = (W, F), displayed in Figure below,
are isomorphic.

Solution:
- The function f with f(u1) = v1, f(u2) = v4, f(u3) = v3, and f (u4) = v2 is a one-to-one
correspondence between V and W.
- To see that this correspondence preserves adjacency, note that adjacent vertices in G are u1
and u2, u1 and u3, u2 and u4, and u3 and u4, and each of the pairs f (u1) = v1 and f (u2) = v4, f
(u1) = v1 and f (u3) = v3, f (u2) = v4 and f (u4) = v2, and f (u3) = v3 and f (u4) = v2 consists of
two adjacent vertices in H.

Path
- Let n be a nonnegative integer and G an undirected graph.

10
- A path of length n from u to v in G is a sequence of n edges e1,...,en of G for which there
exists a sequence x0 = u, x1,...,xn−1, xn = v of vertices such that ei has, for i = 1,...,n, the end
points xi−1 and xi.
- When the graph is simple, we denote this path by its vertex sequence x0, x1,...,xn (because
listing these vertices uniquely determines the path).
- The path is a circuit if it begins and ends at the same vertex, that is, if u = v, and has length
greater than zero.
- The path or circuit is said to pass through the vertices x1, x2,...,xn−1 or traverse the edges
e1, e2,...,en.
- A path or circuit is simple if it does not contain the same edge more than once.

Connectedness in Undirected Graphs


- An undirected graph is called connected if there is a path between every pair of distinct
vertices of the graph.
- An undirected graph that is not connected is called disconnected.
- We say that we disconnect a graph when we remove vertices or edges, or both, to produce a
disconnected subgraph.

Connected Components
- A connected component of a graph G is a connected subgraph of G that is not a proper
subgraph of another connected subgraph of G. That is, a connected component of a graph G
is a maximal connected subgraph of G. A graph G that is not connected has two or more
connected components that are disjoint and have G as their union.

Connectedness in Directed Graphs


- A directed graph is strongly connected if there is a path from a to b and from b to a
whenever a and b are vertices in the graph.
- A directed graph is weakly connected if there is a path between every two vertices in the
underlying undirected graph.

Strong Components of a Directed Graph


- The subgraphs of a directed graph G that are strongly connected but not contained in
larger strongly connected subgraphs, that is, the maximal strongly connected subgraphs,
are called the strongly connected components or strong components of G.
- Note that if a and b are two vertices in a directed graph, their strong components are
either the same or disjoint.

11
Euler Paths and Circuits
- An Euler circuit in a graph G is a simple circuit containing every edge of G.
- An Euler path in G is a simple path containing every edge of G.
EXAMPLE: Check whether the given graph is Euler Graph or not.

Hamilton Paths and Circuits


- A simple path in a graph G that passes through every vertex exactly once is called a
Hamilton path, and a simple circuit in a graph G that passes through every vertex exactly
once is called a Hamilton circuit.
EXAMPLE: Check whether the given graph is Hamilton graph or not.

Shortest-Path Problems
Many problems can be modelled using graphs with weights assigned to their edges. Such as:
➢ Problems involving distances can be modelled by assigning distances between
cities to the edges.
➢ Problems involving flight time can be modelled by assigning flight times to edges.

Weighted Graphs
- Graphs that have a number assigned to each edge are called weighted graphs.
- Weighted graphs are used to model computer networks.

12
- Communications costs (such as the monthly cost of leasing a telephone line), the response
times of the computers over these lines, or the distance between computers, can all be
studied using weighted graphs.
EXAMPLE:

Fig: A Weighted Simple Graph.

Dijkstra’s Algorithm
– This approach is of getting single source shortest paths.

– In this algorithm it is assumed that there is no negative weight edge.

– Dijkstra’s algorithm works using greedy approach.

Algorithm:
Dijkstra(G,w,s)
{
for each vertex v V
do d[v] =
d[s] = 0
S=
Q=V
While(Q!= )
{
u = Take minimum from Q and delete. S
= S {u}
for each vertex v adjacent to u do
if d[v] > d[u] + w(u,v)

13
then d[v] = d[u] + w(u,v)
}
}

EXAMPLE: Find the shortest paths from the source g to all other vertices using Dijkstra’s
algorithm.

Solution:

14
The Traveling Salesperson Problem
A traveling salesperson wants to visit each of n cities exactly once and return to his starting
point.

Planar Graphs
- A graph is called planar if it can be drawn in the plane without any edges crossing (where
a crossing of edges is the intersection of the lines or arcs representing them at a point
other than their common endpoint).
- Such a drawing is called a planar representation of the graph.
EXAMPLE:

15
Graph Colouring
- A colouring of a simple graph is the assignment of a colour to each vertex of the graph so
that no two adjacent vertices are assigned the same colour.

Chromatic number
- The chromatic number of a graph is the least number of colours needed for a colouring of
this graph.
- The chromatic number of a graph G is denoted by χ (G). (Here χ is the Greek letter chi.)

Applications of Graph Colorings


Scheduling Final Exams
- This scheduling problem can be solved using a graph model, with vertices representing
courses and with an edge between two vertices if there is a common student in the courses
they represent.
- Each time slot for a final exam is represented by a different color.
- A scheduling of the exams corresponds to a coloring of the associated graph.
EXAMPLE:
How can the final exams at a university be scheduled so that no student has two exams at the
same time?
Solution:
- For instance, suppose there are seven finals to be scheduled.
- Suppose the courses are numbered 1 through 7.
- Suppose that the following pairs of courses have common students: 1 and 2, 1 and 3, 1
and 4, 1 and 7, 2 and 3, 2 and 4, 2 and 5, 2 and 7, 3 and 4, 3 and 6, 3 and 7, 4 and 5, 4 and
6, 5 and 6, 5 and 7, and 6 and 7.
- In figure below the graph associated with this set of classes is shown.
- A scheduling consists of a coloring of this graph. Because the chromatic number of this
graph is 4, four time slots are needed.
- A coloring of the graph using four colors and the associated schedule are shown in figure
below.

16
Graph Representing Scheduling of Final Exam

Using Coloring to Schedule Final Exam

Schedule of Final Exam

THEOREM: THE FOUR COLOR THEOREM


The chromatic number of a planar graph is no greater than four.

6.2 Trees
Definition of
Tree
A tree is a connected undirected graph with no simple circuits.

Tree Terminologies
Suppose that T is a rooted tree.

Root
- The root node is the topmost node in the tree hierarchy.

Parent and Child


- If v is a vertex in T other than the root, the parent of v is the unique vertex u such that
there is a directed edge from u to v.
- When u is the parent of v, v is called a child of u.

17
Siblings
- Vertices with the same parent are called siblings.

Ancestors
- The ancestors of a vertex other than the root are the vertices in the path from the root to this
vertex, excluding the vertex itself and including the root (that is, its parent, its parent’s
parent, and so on, until the root is reached).

Descendants
- The descendants of a vertex v are those vertices that have v as an ancestor.

Leaf
- A vertex of a rooted tree is called a leaf if it has no children.

Internal vertices
- Vertices that have children are called internal vertices.

Subtree
- If ‘a’ is a vertex in a tree, the subtree with a as its root is the subgraph of the tree consisting
of ‘a’ and its descendants and all edges incident to these descendants.

Fig: A tree T with root a.


EXAMPLE: In the rooted tree T (with root a) shown in Figure above, find the parent of c, the
children of g, the siblings of h, all ancestors of e, all descendants of b, all internal vertices, and
all leaves. What is the subtree rooted at g?
Solution:
- The parent of c is b.
- The children of g are h, i, and j.

18
- The siblings of h are i and j.
- The ancestors of e are c, b, and a.
- The descendants of b are c, d, and e.
- The internal vertices are a, b, c, g, h, and j.
- The leaves are d, e, f, i, k, l, and m.
- The subtree rooted at g is shown in Figure below.

Fig: A subtree with root g.

Applications of trees
The following are the applications of trees:

• Storing naturally hierarchical data: Trees are used to store the data in the hierarchical
structure. For example, the file system. The file system stored on the disc drive, the file
and folder are in the form of the naturally hierarchical data and stored in the form of trees.
• Organize data: It is used to organize data for efficient insertion, deletion and searching.
For example, a binary tree has a logN time for searching an element.
• Trie: It is a special kind of tree that is used to store the dictionary. It is a fast and efficient
way for dynamic spell checking.
• Heap: It is also a tree data structure implemented using arrays. It is used to implement
priority queues.
• B tree and B+ tree: B tree and B+ tree are the tree data structures used to implement
indexing in databases.
• Routing table: The tree data structure is also used to store the data in routing tables in the
routers.

Tree Traversals
- The tree traversal is a way in which each node in the tree is visited exactly once in a
symmetric manner.
- There are three popular methods of traversal
• Pre-order traversal

19
• In-order traversal
• Post-order traversal

Pre-order traversal
- The preorder traversal of a nonempty binary tree is defined as follows:
• Visit the root node
• Traverse the left sub-tree in preorder
• Traverse the right sub-tree in preorder
- The preorder is also known as depth first order.
EXAMPLE:

Fig: A binary tree.


- The preorder traversal of given tree is:
ABDHIECFG

In-order traversal
- The inorder traversal of a nonempty binary tree is defined as follows:
• Traverse the left sub-tree in inorder
• Visit the root node
• Traverse the right sub-tree in inorder
EXAMPLE:
- The inorder traversal output of the given tree is: H D I B E A F C G

Post-order traversal
- The post-order traversal of a nonempty binary tree is defined as follows:
• Traverse the left sub-tree in post-order
• Traverse the right sub-tree in post-order
• Visit the root node
EXAMPLE:
- The post-order traversal output of the given tree is: H I D E B F G C A

20
Spanning Tree
- Let G be a simple graph.
- A spanning tree of G is a subgraph of G that is a tree containing every vertex of G.
EXAMPLE: Find a spanning tree of the simple graph G shown in Figure below.

Solution:
- The graph G is connected, but it is not a tree because it contains simple circuits.
- Remove the edge {a, e}.
- This eliminates one simple circuit, and the resulting subgraph is still connected and still
contains every vertex of G.
- Next remove the edge {e, f} to eliminate a second simple circuit.
- Finally, remove edge {c, g} to produce a simple graph with no simple circuits.
- This subgraph is a spanning tree, because it is a tree that contains every vertex of G.
- The sequence of edge removals used to produce the spanning tree is illustrated in Figure
below.

Fig: Producing a Spanning Tree for G by Removing Edges That Form Simple Circuits.

Minimum Spanning Tree


- A minimum spanning tree in a connected weighted graph is a spanning tree that has the
smallest possible sum of weights of its edges.
- There are two algorithm to find the MST.
➢ Prim’s Algorithm
➢ Kruskal’s Algorithm

21
Kruskal’s Algorithm
- To carry out Kruskal’s algorithm, choose an edge in the graph with minimum weight.
Algorithm:

EXAMPLE: Find the MST and its weight of the graph.

Solution:

22
- The total weight of MST is 64.

Assignment
1. Define Euler path and Hamilton path with examples. [TU 2075]
2. Define spanning tree and minimum spanning tree. Mention the conditions for two
graphs for being isomorphic with an example. (5) [TU 2075]
3. What is meant by chromatic number? How can you use graph colouring to schedule
exams? Justify by using 10 subjects assuming that the pairs {(1,2), (1,5), (1,8), (2,4),
(2,9), (2,7), (3,6), (3,7), (3,10), (4,8), (4,3), (4,10), (5,6), (5,7)} of subjects have
common students. (1+4) [TU Model Question]
4. Define bipartite graph with example. State the necessary conditions for the graphs to
be isomorphic. [TU 2079]

Lab 6
Write a C program to represent relations
Ans: Let A = {3,4,5}, B = {6,7,8} Find relation R on A*B such that x+y<12 where x A and y B
#include<conio.h>
#include<stdio.h>
void createRelation(int A[],int B[],int n1,int n2)
{
printf("{");
for(int i=0;i<n1;i++)
{
for(int j=0;j<n2;j++)
{
if(A[i]+B[j]<13)
{
printf("(%d,%d)",A[i],B[j]);
}
}
}
printf("}");
}
int main()
{
int A[] = {4,5,6};
23
int B[] = {6,7,8,9};
createRelation(A,B,3,4);
getch();
return 0;
}
Output:
{(4,6)(4,7)(4,8)(5,6)(5,7)(6,6)}

Write a C program to test properties of relation


Ans
If R = {(1,1),(1,2),(2,2),(2,3),(3,3)} is a relation on set A = {1,2,3} then test whether R is reflexive
relation or not.
#include<conio.h>
#include<stdio.h>
#define N 3
#define ROW 5
#define COL 2
void isRelationReflexive(int A[],int R[][2],int n,int r,int c)
{
int t=0;
for(int i=0;i<n;i++)
{
for(int j=0;j<r;j++)
{
for(int k=0;k<c-1;k++)
{
if(A[i]== R[j][k]&&A[i]==R[j][k+1])
t++;
}
}
}
if(t==3)
printf("The relation is reflexive");
else
printf("The relation is not reflexive");
}
int main()
{
int A[] = {1,2,3};
int R[5][2] = {{1,1},{1,2},{2,2},{2,3},{3,3}};
isRelationReflexive(A,R,N,ROW,COL);
getch();
return 0;
}
Output:
The relation is reflexive

Write a C program to represent graph.


Ans:
#include<conio.h>
#include<stdio.h>
void print_graph(int adj[20][20],int n);
void read_graph(int a[20][20],int n);
int main()
{
printf("program to represent a undirected grapg using adjacency matrix\n");
int adj[20][20];
read_graph(adj,20);
24
getch();
return 0;
}
void read_graph(int adj[20][20],int N)
{
int i,j;
int n;
printf("Enter number of vertices\n");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
if(i==j)
{
adj[i][j]=0;
continue;
}
printf("is there edge from vertex %d to %d then enter 1 otherwise 0\n",i,j);
scanf("%d",&adj[i][j]);
}
}
printf("The adjacency matrix representation of graph\n");
print_graph(adj,n);
}
void print_graph(int adj[20][20],int n)
{
int i,j;
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
printf("%d ",adj[i][j]);
}
printf("\n");
}
}
Output:
program to represent a undirected grapg using adjacency ma
Enter number of vertices
5
is there edge from vertex 1 to 2 then enter 1 otherwise 0
1
is there edge from vertex 1 to 3 then enter 1 otherwise 0
1
is there edge from vertex 1 to 4 then enter 1 otherwise 0
0
is there edge from vertex 1 to 5 then enter 1 otherwise 0
1
is there edge from vertex 2 to 1 then enter 1 otherwise 0
0
is there edge from vertex 2 to 3 then enter 1 otherwise 0
1
is there edge from vertex 2 to 4 then enter 1 otherwise 0
0
is there edge from vertex 2 to 5 then enter 1 otherwise 0
1
is there edge from vertex 3 to 1 then enter 1 otherwise 0
25
0
is there edge from vertex 3 to 2 then enter 1 otherwise 0
1
is there edge from vertex 3 to 4 then enter 1 otherwise 0
0
is there edge from vertex 3 to 5 then enter 1 otherwise 0
1
is there edge from vertex 4 to 1 then enter 1 otherwise 0
0
is there edge from vertex 4 to 2 then enter 1 otherwise 0
1
is there edge from vertex 4 to 3 then enter 1 otherwise 0
0
is there edge from vertex 4 to 5 then enter 1 otherwise 0
1
is there edge from vertex 5 to 1 then enter 1 otherwise 0
0
is there edge from vertex 5 to 2 then enter 1 otherwise 0
1
is there edge from vertex 5 to 3 then enter 1 otherwise 0
0
is there edge from vertex 5 to 4 then enter 1 otherwise 0
1
The adjacency matrix representation of graph
01101
00101
01001
01001
01010
Write a C program to find shortest path(Dijkstra's Algorithm)
Ans:
#include<stdio.h>
#include<conio.h>
#define INFINITY 9999
#define MAX 10
void dijkstra(int G[MAX][MAX],int n,int startnode);
int main()
{
int G[MAX][MAX],i,j,n,u;
printf("Enter no. of vertices:");
scanf("%d",&n);
printf("\nEnter the adjacency matrix:\n");
for(i=0;i<n;i++)
for(j=0;j<n;j++)
scanf("%d",&G[i][j]);
printf("\nEnter the starting node:");
scanf("%d",&u);
dijkstra(G,n,u);
return 0;
}

void dijkstra(int G[MAX][MAX],int n,int startnode)


{
int cost[MAX][MAX],distance[MAX],pred[MAX];
int visited[MAX],count,mindistance,nextnode,i,j;
//pred[] stores the predecessor of each node
//count gives the number of nodes seen so far
//create the cost matrix
26
for(i=0;i<n;i++)
for(j=0;j<n;j++)
if(G[i][j]==0)
cost[i][j]=INFINITY;
else
cost[i][j]=G[i][j];

//initialize pred[],distance[] and visited[]


for(i=0;i<n;i++)
{
distance[i]=cost[startnode][i];
pred[i]=startnode;
visited[i]=0;
}
distance[startnode]=0;
visited[startnode]=1;
count=1;
while(count<n-1)
{
mindistance=INFINITY;
//nextnode gives the node at minimum distance
for(i=0;i<n;i++)
if(distance[i]<mindistance&&!visited[i])
{
mindistance=distance[i];
nextnode=i;
}
//check if a better path exists through nextnode
visited[nextnode]=1;
for(i=0;i<n;i++)
if(!visited[i])
if(mindistance+cost[nextnode][i]<distance[i])
{
distance[i]=mindistance+cost[nextnode][i];
pred[i]=nextnode;
}
count++;
}
//print the path and distance of each node
for(i=0;i<n;i++)
if(i!=startnode)
{
printf("\nDistance of node%d=%d",i,distance[i]);
printf("\nPath=%d",i);
j=i;
do
{
j=pred[j];
printf("<-%d",j);
}while(j!=startnode);
}
}
Output
Enter no. of vertices:5
Enter the adjacency matrix:
0 12 0 0 6
12 0 5 6 2
05003
27
0 6 0 0 10
6 2 3 10 0

Enter the starting node:1

Distance of node0=8
Path=0<-4<-1
Distance of node2=5
Path=2<-1
Distance of node3=6
Path=3<-1
Distance of node4=2
Path=4<-1
Write a C program to find minimum spanning tree (Kruskal's Algorithm)
Ans:
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
int i,j,k,a,b,u,v,n,ne=1;
int min,mincost=0,cost[9][9],parent[9];
int find(int);
int uni(int,int);
int main()
{
printf("Implementation of Kruskal's algorithm\n");
printf("Enter the no. of vertices\n");
scanf("%d",&n);
printf("\nEnter the cost adjacency matrix\n");
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
printf("Enter wt from vertex %d to %d\n",i,j);
scanf("%d",&cost[i][j]);
if(cost[i][j]==0)
cost[i][j]=999;
}
}
printf("\nThe edges of Minimum Cost Spanning Tree are\n");
while(ne<n)
{
for(i=1,min=999;i<=n;i++)
{
for(j=1;j<=n;j++)
{
if(cost[i][j]<min)
{
min=cost[i][j];
a=u=i;
b=v=j;
}
}
}
u=find(u);
v=find(v);
if(uni(u,v))
{
printf("\n%d edge (%d,%d) =%d\n",ne++,a,b,min);
28
mincost +=min;
}
cost[a][b]=cost[b][a]=999;
}
printf("\nMinimum cost = %d\n",mincost);
getch();
}
int find(int i)
{
while(parent[i])
i=parent[i];
return i;
}
int uni(int i,int j)
{
if(i!=j)
{
parent[j]=i;
return 1;
}
return 0;
}
Output:
Implementation of Kruskal's algorithm
Enter the no. of vertices
5

Enter the cost adjacency matrix


Enter wt from vertex 1 to 1
0
Enter wt from vertex 1 to 2
3
Enter wt from vertex 1 to 3
0
Enter wt from vertex 1 to 4
4
Enter wt from vertex 1 to 5
1
Enter wt from vertex 2 to 1
3
Enter wt from vertex 2 to 2
0
Enter wt from vertex 2 to 3
4
Enter wt from vertex 2 to 4
0
Enter wt from vertex 2 to 5
0
Enter wt from vertex 3 to 1
0
Enter wt from vertex 3 to 2
4
Enter wt from vertex 3 to 3
0
Enter wt from vertex 3 to 4
3
Enter wt from vertex 3 to 5
2
29
Enter wt from vertex 4 to 1
4
Enter wt from vertex 4 to 2
0
Enter wt from vertex 4 to 3
3
Enter wt from vertex 4 to 4
0
Enter wt from vertex 4 to 5
1
Enter wt from vertex 5 to 1
1
Enter wt from vertex 5 to 2
0
Enter wt from vertex 5 to 3
2
Enter wt from vertex 5 to 4
1
Enter wt from vertex 5 to 5
0

The edges of Minimum Cost Spanning Tree are

1 edge (1,5) =1

2 edge (4,5) =1

3 edge (3,5) =2

4 edge (1,2) =3

Minimum cost = 7

30

You might also like