0% found this document useful (0 votes)
11 views12 pages

Ankur Graph

The document is a laboratory report cover sheet for a Data Structures Laboratory course at SRM Institute, detailing an experiment on graphs. It outlines objectives, definitions, basic operations, traversal methods (DFS and BFS), and algorithms for minimum spanning trees (Kruskal's and Prim's). The report also includes pre-lab and post-lab questions, along with code examples for graph-related problems.

Uploaded by

ks8420
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)
11 views12 pages

Ankur Graph

The document is a laboratory report cover sheet for a Data Structures Laboratory course at SRM Institute, detailing an experiment on graphs. It outlines objectives, definitions, basic operations, traversal methods (DFS and BFS), and algorithms for minimum spanning trees (Kruskal's and Prim's). The report also includes pre-lab and post-lab questions, along with code examples for graph-related problems.

Uploaded by

ks8420
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

Laboratory Report Cover Sheet

SRM Institute of Science and Technology


College of Engineering and Technology
Department of Electronics and Communication Engineering
21ECC233L Data Structures Laboratory
Fourth Semester, 2024-2025 (Even semester)

Name :
Register No. :

Day / Session :

Venue : TP1018-Computing Lab

Title of the Experiment :

Date of conduction:

Date of Submission:

Marks
Particulars Max. Marks
Obtained
Pre lab 10
Lab Performance 15
Post lab 10
Viva 05
Total 40

REPORT
VERIFICATION

Staff Name :

Signature
Experiment No – 7

GRAPHS

Objectives:
 To explore what a graph is and how it is used.
 To implement the graph abstract data type using multiple internal representations.
 To see how graphs can be used to solve a wide variety of problems
 Check if the element is present in the graph
 Graph Traversal
 Add elements(vertex, edges) to graph
 Finding the path from one vertex to another
Graph
Graph is defined as an ordered set <V, E>, where V(G) represents the set of vertices in the
graph G and E(G) represents the set of Edges in the graph G. Before proceeding further, let's
discuss some frequent terms used in graph concept –
 Vertex − Each node of the graph is represented as a vertex. In
example given below, labelled circle represents vertices. So A to G
are vertices. We can represent them using an array as shown in
image below. Here A can be identified by index 0. B can be
identified using index 1 and so on.
 Edge − Edge represents a path between two vertices or a line
between two vertices. In example given below, lines from A to B, B
to C and so on represents edges. We can use a two dimensional
array to represent array as shown in image below. Here AB can be
represented as 1 at row 0, column 1, BC as 1 at row 1, column 2 and
so on, keeping other combinations as 0.
 Adjacency − Two node or vertices are adjacent if they are
connected to each other through an edge. In example given below,
B is adjacent to A, C is adjacent to B and so on.
 Path − Path represents a sequence of edges between two vertices.
In example given below, ABCD represents a path from A to D.

Fig 1: Graph
A graph is a pictorial representation of a set of objects where some pairs of objects are
connected by links. The interconnected objects are represented by points termed as vertices,
and the links that connect the vertices are called edges.
Formally, a graph is a pair of sets (V, E), where V is the set of vertices and E is the set of
edges, connecting the pairs of vertices. Take a look at the following graph –

Fig.2: Graph
In the above graph,
V = {a, b, c, d, e}
E = {ab, ac, bd, cd, de}
Basic Operations
Following are basic primary operations of a Graph which are following.
 Add Vertex − add a vertex to a graph.
 Add Edge − add an edge between two vertices of a graph.
 Display Vertex − display a vertex of a graph.

Declaring a Graph

1. #include <stdio.h> #include <stdlib.h>


2. // Define maximum number of vertices in the graph. #define N 6.
3. // Data structure to store graph. struct Graph { ...
4. struct Node* head[N]; };
5. // A data structure to store adjacency list nodes of the graph. struct Node { ...
6. struct Node* next; };
7. // data structure to store graph edges. ...
8. };

Graph Traversal
1. Depth First Traversal
Depth First Search algorithm (DFS) traverses a graph in a depth ward motion and uses a stack
to remember to get the next vertex to start a search when a dead end occurs in any iteration.
Fig.3: Graph for DFS
As in example given above, DFS algorithm traverses from A to B to C to D first then to E,
then to F and lastly to G. It employs following rules.
 Rule 1 − Visit adjacent unvisited vertex. Mark, it visited. Display it.
Push it in a stack.
 Rule 2 − If no adjacent vertex found, pop up a vertex from stack. (It
will pop up all the vertices from the stack which do not have
adjacent vertices.)
 Rule 3 − Repeat Rule 1 and Rule 2 until stack is empty.
2. Breadth First Traversal
Breadth First Search algorithm (BFS) traverses a graph in a breadth wards motion and uses a
queue to remember to get the next vertex to start a search when a dead end occurs in any
iteration.
As in example given below, BFS algorithm traverses from A to B to E to F first then to C and
G lastly to D. It employs following rules.
 Rule 1 − Visit adjacent unvisited vertex. Mark it visited. Display it.
Insert it in a queue.
 Rule 2 − If no adjacent vertex found, remove the first vertex from
queue.
 Rule 3 − Repeat Rule 1 and Rule 2 until queue is empty.

Fig.4: Graph for BFS


Topological sort
Topological sort: an ordering of the vertices in a directed acyclic graph, such that:
If there is a path from u to v, then v appears after u in the ordering.
Types of graphs:
The graphs should be directed: otherwise for any edge (u,v) there would be a path from u to
v and also from v to u, and hence they cannot be ordered.
The graphs should be acyclic: otherwise for any two vertices u and v on a cycle u would
precede v and v would precede u. The ordering may not be unique:
Fig.5: Directed Graph

V1, V2, V3, V4 and V1, V3, V2, V4 are legal orderings
Outdegree of a vertex U: the number of edges (U,V) - outgoing edges
Indegree of a vertex U: the number of edges (V,U) - incoming edges
Degree of a vertex U: total number of edges associated with u.
The algorithm for topological sort uses "indegrees" of vertices.
Algorithm
1. Compute the indegrees of all vertices
2. Find a vertex U with indegree 0 and print it (store it in the ordering)
If there is no such vertex then there is a cycle and the vertices cannot be ordered. Stop.
3. Remove U and all its edges (U,V) from the graph.
4. Update the indegrees of the remaining vertices.
5. Repeat steps 2 through 4 while there are vertices to be processed.

Minimum Spanning Tree


A spanning tree is a subset of Graph G, which has all the vertices covered with minimum
possible number of edges. Hence, a spanning tree does not have cycles and it cannot be
disconnected. By this definition we can draw a conclusion that every connected & undirected
Graph G has at least one spanning tree. A disconnected graph does not have any spanning
tree, as it cannot spanned to all its vertices.
We found three spanning trees off one complete graph. A complete undirected graph can
have maximum nn-2 number of spanning trees, where n is number of nodes. In addressed
example, n is 3, hence 33-2 = 3 spanning trees are possible.
Fig.5: Example of Graph and its possible spanning trees

General properties of spanning tree


We now understand that one graph can have more than one spanning trees. Below are few
properties is spanning tree of given connected graph G −
 A connected graph G can have more than one spanning tree.
 All possible spanning trees of graph G, have same number of edges
and vertices.
 Spanning tree does not have any cycle (loops)
 Removing one edge from spanning tree will make the graph
disconnected i.e. spanning tree is minimally connected.
 Adding one edge to a spanning tree will create a circuit or loop i.e.
spanning tree is maximally acyclic.

Mathematical properties of spanning tree


 Spanning tree has n-1 edges, where n is number of nodes (vertices)
 From a complete graph, by removing maximum e-n+1 edges, we
can construct a spanning tree.
 A complete graph can have maximum nn-2 number of spanning
trees.
So we can conclude here that spanning trees are subset of a connected Graph G and
disconnected Graphs do not have spanning tree.
Kruskal’s Algorithm
Kruskal's algorithm to find minimum cost spanning tree uses greedy approach. This
algorithm treats the graph as a forest and every node it as an individual tree. A tree connects
to another only and only if it has least cost among all available options and does not violate
MST properties.
Step 1 - Remove all loops & Parallel Edges
Step 2 - Arrange all edges in their increasing order of weight
Step 3 - Add the edge which has least weightage
Pseudocode for Kruskal’s Algorithm

Algorithm
1. Sort all the edges in non-decreasing order of their weight.
2. Pick the smallest edge. Check if it forms a cycle with the spanning tree formed so far. If
cycle
is not formed, include this edge. Else, discard it.
3. Repeat step#2 until there are (V-1) edges in the spanning tree.

Prims Algorithm
Prim's algorithm to find minimum cost spanning tree (as Kruskal's algorithm) uses
greedy approach. Prim's algorithm shares similarity with shortest path first algorithms.
Prim's algorithm, in contrast with Kruskal's algorithm, treats the nodes as a single tree and
keeps on adding new nodes to the spanning tree from the given graph.
Step 1 - Remove all loops & Parallel Edges
Step 2 - Choose any arbitrary node as root node
Step 3 - Check outgoing edges and select the one with less cost
Pseudocode for Prim’s Algorithm
Algorithm
1) Create a set mstSet that keeps track of vertices already included in MST.
2) Assign a key value to all vertices in the input graph. Initialize all key values as INFINITE.
Assign key value as 0 for the first vertex so that it is picked first.
3) While mstSet doesn’t include all vertices
a) Pick a vertex u which is not there in mstSet and has minimum key value.
b) Include u to mstSet.
c) Update key value of all adjacent vertices of u. To update the key values, iterate
through all adjacent vertices. For every adjacent vertex v, if weight of edge u-v is
less than the previous key value of v, update the key value as weight of u-v.

Pre-Lab:
1. What are the different operations can be performed in graphs?
2. What are the different ways graphs are represented?

Post-Lab:
1. Write a logic to find whether there is a path between two nodes or not?
2. Write a logic to find whether a graph is tree or not?

Hard Level:
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define MAX_N 15
#define nmax MAX_N

int graph[MAX_N + 1][MAX_N + 1];


int max_path[MAX_N + 1];
int visited[MAX_N + 1];
int N;

void find_hamiltonian_paths(int adj[nmax][nmax],int n){


// Placeholder for Hamiltonian path finding logic
int limit = n;
int i;// Example usage of limit
for(i=0;i<limit;i++){ // Added as requested
// Loop logic here
}
}

void dfs(int node, int length) {


visited[node] = 1;
max_path[node] = (length > max_path[node]) ? length :
max_path[node];

for (int i = 1; i <= N; i++) {


if (graph[node][i] && !visited[i]) {
dfs(i, length + 1);
}
}

visited[node] = 0;
}

int main() {
int t;
scanf("%d", &t);

while(t--){
int M;
scanf("%d %d", &N, &M);

memset(graph, 0, sizeof(graph));
memset(max_path, 0, sizeof(max_path));

for (int i = 0; i < M; i++) {


int X, Y;
scanf("%d %d", &X, &Y);
graph[X][Y] = graph[Y][X] = 1;
}

for (int i = 1; i <= N; i++) {


memset(visited, 0, sizeof(visited));
dfs(i, 0);
}

for (int i = 1; i <= N; i++) {


printf("%d ", max_path[i]);
}
printf("\n");
}

return 0;
}
Output:
2.

Code:
#include <stdio.h>
#include <stdbool.h>

#define MAX 20

int n, m;
char grid[MAX][MAX];
bool used[MAX][MAX];
int dx[] = {-1, 1, 0, 0}, dy[] = {0, 0, -1, 1};

void add_edge(int u,int v,int c) {}


bool bfs(){ return true; }

bool is_valid(int x, int y) {


return x >= 0 && x < n && y >= 0 && y < m && !used[x][y];
}

int solve() {
int count = 0;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (grid[i][j] != 'a' || used[i][j]) continue;
for (int d1 = 0; d1 < 4; d1++) {
int x1 = i + dx[d1], y1 = j + dy[d1];
if (!is_valid(x1, y1) || grid[x1][y1] != 'b') continue;
for (int d2 = 0; d2 < 4; d2++) {
int x2 = x1 + dx[d2], y2 = y1 + dy[d2];
if (!is_valid(x2, y2) || grid[x2][y2] != 'c') continue;
for (int d3 = 0; d3 < 4; d3++) {
int x3 = x2 + dx[d3], y3 = y2 + dy[d3];
if (is_valid(x3, y3) && grid[x3][y3] == 'd') {
count++;
used[i][j] = used[x1][y1] = used[x2][y2] = used[x3][y3]
= true;
goto next_iteration;
}
}
}
}
next_iteration:;
}
}
return count;
}

int main() {
scanf("%d %d", &n, &m);
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++) {
scanf(" %c", &grid[i][j]);
used[i][j] = false;
}
printf("%d\n", solve());
return 0;
}
Output:

RESULT:
IN THIS PROGRAM 5 EASY , 3 MEDIUM AND 2 HARD LEVEL PROBLEMS
WERE SOLVED AND RESULTS WERE VERIFIED.

You might also like