You are on page 1of 10

BEYOND SYLLABUS

1. Write a C program to create and represent a graph using adjacency matrix.

CODE:

#include <stdio.h>

#define MAX_VERTICES 100

int adjMatrix[MAX_VERTICES][MAX_VERTICES];

// Function to add an edge to the adjacency matrix


void addEdge(int from, int to) {
adjMatrix[from][to] = 1;
adjMatrix[to][from] = 1; // Assuming an undirected graph
}

// Function to display the adjacency matrix


void displayMatrix(int vertices) {
printf("Adjacency Matrix:\n");
for (int i = 0; i < vertices; i++) {
for (int j = 0; j < vertices; j++) {
printf("%d ", adjMatrix[i][j]);
}
printf("\n");
}
}

int main() {
int vertices, edges;

printf("Enter the number of vertices: ");


scanf("%d", &vertices);

printf("Enter the number of edges: ");


scanf("%d", &edges);

// Initialize the adjacency matrix with zeros


for (int i = 0; i < MAX_VERTICES; i++) {
for (int j = 0; j < MAX_VERTICES; j++) {
adjMatrix[i][j] = 0;
}
}

// Input edges to build the graph


for (int i = 0; i < edges; i++) {
int from, to;
printf("Enter edge %d (format: from to): ", i + 1);
scanf("%d %d", &from, &to);
addEdge(from, to);
}

// Display the adjacency matrix


displayMatrix(vertices);

return 0;
}

ALGORITHM:

// Include necessary header files


#include <stdio.h>

// Define constant for maximum vertices


MAX_VERTICES = 100

// Declare global adjacency matrix


int adjMatrix[MAX_VERTICES][MAX_VERTICES]

// Function to add an edge to the adjacency matrix


function addEdge(from, to):
adjMatrix[from][to] = 1
adjMatrix[to][from] = 1 // Assuming an undirected graph

// Function to display the adjacency matrix


function displayMatrix(vertices):
print "Adjacency Matrix:"
for i from 0 to vertices - 1:
for j from 0 to vertices - 1:
print adjMatrix[i][j],
print newline

// Main function
function main():
// Declare local variables
int vertices, edges

// Input the number of vertices from the user


print "Enter the number of vertices: "
scan vertices

// Input the number of edges from the user


print "Enter the number of edges: "
scan edges

// Initialize the adjacency matrix with zeros


for i from 0 to MAX_VERTICES - 1:
for j from 0 to MAX_VERTICES - 1:
adjMatrix[i][j] = 0

// Input edges to build the graph


for i from 0 to edges - 1:
// Input edge in the format: from to
print "Enter edge ", i + 1, " (format: from to): "
scan from, to
addEdge(from, to)

// Display the adjacency matrix


displayMatrix(vertices)

// Return 0 to indicate successful execution


return 0

// End of program

OUTPUT:

DISCUSSION: 1. Time Complexity:


- Creating the graph involves initializing the adjacency matrix, which is done in O(V^2)
time, where V is the number of vertices.
- Adding an edge using the addEdge function takes constant time, O(1), as it involves
updating a single entry in the matrix.

Therefore, the overall time complexity of creating and representing a graph using an
adjacency matrix is O(V^2).

2. Space Complexity:
- The space complexity is determined by the size of the adjacency matrix, which is V x V.
- Hence, the space complexity is O(V^2), where V is the number of vertices.
2. Write a C program for implementing breadth first search (BFS) in a graph.

CODE:

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

#define MAX_VERTICES 50

// This struct represents a directed graph using


// adjacency list representation
typedef struct Graph_t {

// No. of vertices
int V;
bool adj[MAX_VERTICES][MAX_VERTICES];
} Graph;

// Constructor
Graph* Graph_create(int V)
{
Graph* g = malloc(sizeof(Graph));
g->V = V;

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


for (int j = 0; j < V; j++) {
g->adj[i][j] = false;
}
}

return g;
}

// Destructor
void Graph_destroy(Graph* g) { free(g); }

// Function to add an edge to graph


void Graph_addEdge(Graph* g, int v, int w)
{
// Add w to v’s list.
g->adj[v][w] = true;
}

// Prints BFS traversal from a given source s


void Graph_BFS(Graph* g, int s)
{
// Mark all the vertices as not visited
bool visited[MAX_VERTICES];
for (int i = 0; i < g->V; i++) {
visited[i] = false;
}

// Create a queue for BFS


int queue[MAX_VERTICES];
int front = 0, rear = 0;

// Mark the current node as visited and enqueue it


visited[s] = true;
queue[rear++] = s;

while (front != rear) {

// Dequeue a vertex from queue and print it


s = queue[front++];
printf("%d ", s);

// Get all adjacent vertices of the dequeued


// vertex s.
// If an adjacent has not been visited,
// then mark it visited and enqueue it
for (int adjacent = 0; adjacent < g->V;
adjacent++) {
if (g->adj[s][adjacent] && !visited[adjacent]) {
visited[adjacent] = true;
queue[rear++] = adjacent;
}
}
}
}

// Driver code
int main()
{
// Create a graph
Graph* g = Graph_create(4);
Graph_addEdge(g, 0, 1);
Graph_addEdge(g, 0, 2);
Graph_addEdge(g, 1, 2);
Graph_addEdge(g, 2, 0);
Graph_addEdge(g, 2, 3);
Graph_addEdge(g, 3, 3);

printf("Following is Breadth First Traversal "


"(starting from vertex 2) \n");
Graph_BFS(g, 2);
Graph_destroy(g);

return 0;
}

ALGORITHM:

Graph Structure:
Structure Graph:
Integer V
Boolean adj[MAX_VERTICES][MAX_VERTICES]

Graph Creation:
Function Graph_create(V):
graph = Allocate memory for Graph structure
graph.V = V
For i from 0 to V-1:
For j from 0 to V-1:
graph.adj[i][j] = false
Return graph

Graph Destruction:
Function Graph_destroy(graph):
Deallocate memory for graph

Adding an Edge:
Function Graph_addEdge(graph, v, w):
Set graph.adj[v][w] = true

BFS Traversal:
Function Graph_BFS(graph, s):
Array visited[MAX_VERTICES]
For i from 0 to graph.V-1:
visited[i] = false

Queue queue[MAX_VERTICES]
Front = 0, Rear = 0

visited[s] = true
Enqueue(queue, s)

While Front is not equal to Rear:


currentVertex = Dequeue(queue)
Print currentVertex

For adjacent from 0 to graph.V-1:


If graph.adj[currentVertex][adjacent] is true and visited[adjacent] is false:
visited[adjacent] = true
Enqueue(queue, adjacent)

Main Function:
Function main():
graph = Graph_create(4)
Graph_addEdge(graph, 0, 1)
Graph_addEdge(graph, 0, 2)
Graph_addEdge(graph, 1, 2)
Graph_addEdge(graph, 2, 0)
Graph_addEdge(graph, 2, 3)
Graph_addEdge(graph, 3, 3)

Print "Following is Breadth First Traversal (starting from vertex 2)"


Graph_BFS(graph, 2)

Graph_destroy(graph)
Return 0

OUTPUT:

DISCUSSION:
The time complexity of BFS algorithm is O(V+E), since in the worst case, BFS algorithm
explores every node and edge. In a graph, the number of vertices is O(V), whereas the
number of edges is O(E).

3. Write a C program for implementing depth first search (DFS) in a graph.

CODE:
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>

// Structure for a node in the adjacency list


struct Node {
int data;
struct Node* next;
};

// Structure for the adjacency list


struct List {
struct Node* head;
};

// Structure for the graph


struct Graph {
int vertices;
struct List* array;
};

// Function to create a new node


struct Node* createNode(int data) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = data;
newNode->next = NULL;
return newNode;
}

// Function to create a graph with a given number of vertices


struct Graph* createGraph(int vertices) {
struct Graph* graph = (struct Graph*)malloc(sizeof(struct Graph));
graph->vertices = vertices;
graph->array = (struct List*)malloc(vertices * sizeof(struct List));

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


graph->array[i].head = NULL;
}

return graph;
}

// Function to add an edge to the graph


void addEdge(struct Graph* graph, int src, int dest) {
struct Node* newNode = createNode(dest);
newNode->next = graph->array[src].head;
graph->array[src].head = newNode;

// Uncomment the following code to make the graph undirected


/*
newNode = createNode(src);
newNode->next = graph->array[dest].head;
graph->array[dest].head = newNode;
*/
}

// Function to perform Depth First Search (DFS) from a given vertex


void DFS(struct Graph* graph, int vertex, bool visited[]) {
visited[vertex] = true;
printf("%d ", vertex);
struct Node* currentNode = graph->array[vertex].head;
while (currentNode) {
int adjacentVertex = currentNode->data;
if (!visited[adjacentVertex]) {
DFS(graph, adjacentVertex, visited);
}
currentNode = currentNode->next;
}
}

// Function to perform DFS traversal from a given vertex in a specified order


void DFSTraversal(struct Graph* graph, int* order, int orderSize) {
bool* visited = (bool*)malloc(graph->vertices * sizeof(bool));
for (int i = 0; i < graph->vertices; i++) {
visited[i] = false;
}

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


if (!visited[order[i]]) {
DFS(graph, order[i], visited);
}
}

free(visited);
}

int main() {
int vertices = 4;
struct Graph* graph = createGraph(vertices);

addEdge(graph, 2, 0);
addEdge(graph, 0, 2);
addEdge(graph, 1, 2);
addEdge(graph, 0, 1);
addEdge(graph, 3, 3);
addEdge(graph, 1, 3);

int order[] = {2, 0, 1, 3};


int orderSize = sizeof(order) / sizeof(order[0]);

printf("Following is Depth First Traversal (starting from vertex 2):\n");


DFSTraversal(graph, order, orderSize);

return 0;
}

ALGORITHM:
1. **Structures:**
- `struct Node`: Represents a node in the adjacency list.
- `struct List`: Represents the adjacency list for a vertex.
- `struct Graph`: Represents the graph containing an array of adjacency lists.

2. **Functions:**
- `createNode`: Creates a new node with the given data.
- `createGraph`: Creates a new graph with a specified number of vertices.
- `addEdge`: Adds an edge between two vertices in the graph.
- `DFS`: Performs Depth First Search from a given vertex using recursion.
- `DFSTraversal`: Performs DFS traversal from a given set of vertices in a specified order.

3. **Main Function:**
- Creates a graph with 4 vertices.
- Adds edges to the graph using the `addEdge` function.
- Defines an order of vertices for DFS traversal.
- Calls `DFSTraversal` function to perform DFS starting from vertex 2.

4. **Output:**
- The program prints the Depth First Traversal starting from vertex 2 based on the
specified order.

OUTPUT:

DISCUSSION:
For each vertex, DFS visits all its adjacent vertices recursively. In the worst case, DFS may
visit all vertices and edges in the graph. Therefore, the time complexity of DFS is O(V + E),
where V represents the number of vertices and E represents the number of edges in the
graph.

You might also like