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

DAA Termworkkk

The document outlines several algorithms and their implementations for solving various graph and optimization problems, including pathfinding in graphs using DFS, the Fractional Knapsack Problem, Job Sequencing, Minimum Spanning Trees using Kruskal's and Prim's algorithms, and Dijkstra's algorithm for shortest paths. Each section includes a problem statement, objective, algorithm, and code snippets in C. The focus is on designing efficient algorithms to solve specific computational problems related to graphs and optimization.
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 views32 pages

DAA Termworkkk

The document outlines several algorithms and their implementations for solving various graph and optimization problems, including pathfinding in graphs using DFS, the Fractional Knapsack Problem, Job Sequencing, Minimum Spanning Trees using Kruskal's and Prim's algorithms, and Dijkstra's algorithm for shortest paths. Each section includes a problem statement, objective, algorithm, and code snippets in C. The focus is on designing efficient algorithms to solve specific computational problems related to graphs and optimization.
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/ 32

12.

PROBLEM STATEMENT:
Given a (directed/undirected) graph, design an algorithm and implement it using a program to
find if a path exists between two given vertices or not. (Hint: use DFS)

OBJECTIVE:
To design and implement an algorithm using DFS (Depth First Search) to determine
whether a path exists between two given vertices in a directed or undirected graph.

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

#define MAX 100


struct Node {
int vertex;
struct Node* next;
};
struct Graph {
int numVertices;
struct Node** adjLists;
bool* visited;
};
struct Node* createNode(int v) {
struct Node* newNode = malloc(sizeof(struct Node));
newNode->vertex = v;
newNode->next = NULL;
return newNode;
}
struct Graph* createGraph(int vertices) {
struct Graph* graph = malloc(sizeof(struct Graph));
graph->numVertices = vertices;
graph->adjLists = malloc(vertices * sizeof(struct Node*));
graph->visited = malloc(vertices * sizeof(bool));

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


graph->adjLists[i] = NULL;
graph->visited[i] = false;
}

return graph;
}

void addEdge(struct Graph* graph, int src, int dest, bool isDirected) {
struct Node* newNode = createNode(dest);
newNode->next = graph->adjLists[src];
graph->adjLists[src] = newNode;

if (!isDirected) {
newNode = createNode(src);
newNode->next = graph->adjLists[dest];
graph->adjLists[dest] = newNode;
}
}
bool DFS(struct Graph* graph, int src, int dest) {
graph->visited[src] = true;
if (src == dest)
return true;
struct Node* temp = graph->adjLists[src];
while (temp != NULL) {
int connectedVertex = temp->vertex;

if (!graph->visited[connectedVertex]) {
if (DFS(graph, connectedVertex, dest))
return true;
}
temp = temp->next;
}
return false;
}
int main() {
int vertices, edges;
int isDirected;
printf("Enter number of vertices: ");
scanf("%d", &vertices);
printf("Is the graph directed? (1 for Yes, 0 for No): ");
scanf("%d", &isDirected);

struct Graph* graph = createGraph(vertices);


printf("Enter number of edges: ");
scanf("%d", &edges);
printf("Enter edges (source destination):\n");
for (int i = 0; i < edges; i++) {
int src, dest;
scanf("%d %d", &src, &dest);
addEdge(graph, src, dest, isDirected);
}
int start, end;
printf("Enter source and destination vertices to check path: ");
scanf("%d %d", &start, &end);
for (int i = 0; i < vertices; i++)
graph->visited[i] = false;
if (DFS(graph, start, end))
printf("Path exists between %d and %d\n", start, end);
else
printf("No path exists between %d and %d\n", start, end);
return 0;
}
13.PROBLEM STATEMENT:
We are given a set of items, each with a weight and a value. We are also given a knapsack
that has a weight capacity. Write a program to determine the maximum value that can be
carried in the knapsack. In this problem, we can take fractions of items (Program for
knapsack using greedy approach).

OBJECTIVE:
To design and implement a program that solves the Fractional Knapsack Problem using a
greedy algorithm. Given weights and values of items along with a maximum weight
capacity of a knapsack, determine the maximum total value that can be carried, allowing
fractions of items to be included.

ALGORITHM:
CODE:
#include <stdio.h>
#include <stdlib.h>
struct Item {
int value, weight;
};
int compare(const void* a, const void* b) {
double r1 = (double)((struct Item*)a)->value / ((struct Item*)a)->weight;
double r2 = (double)((struct Item*)b)->value / ((struct Item*)b)->weight;
return (r2 > r1) - (r2 < r1);
}
double fractionalKnapsack(int capacity, struct Item items[], int n) {
qsort(items, n, sizeof(struct Item), compare);
double totalValue = 0.0;

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


if (capacity >= items[i].weight) {
capacity -= items[i].weight;
totalValue += items[i].value;
} else {
totalValue += (double)items[i].value * ((double)capacity / items[i].weight);
break;
}
}
return totalValue;
}
int main() {
int n, capacity;
printf("Enter number of items: ");
scanf("%d", &n);

struct Item items[n];


printf("Enter value and weight of each item:\n");
for (int i = 0; i < n; i++) {
printf("Item %d - Value: ", i + 1);
scanf("%d", &items[i].value);
printf("Item %d - Weight: ", i + 1);
scanf("%d", &items[i].weight);
}
printf("Enter capacity of knapsack: ");
scanf("%d", &capacity);
double maxValue = fractionalKnapsack(capacity, items, n);
printf("Maximum value in knapsack = %.2lf\n", maxValue);

return 0;
}
14.PROBLEM STATEMENT:
You are given a set of jobs, each with a specific deadline and associated profit. The objective
is to determine the maximum profit achievable by scheduling these jobs within their
respective deadlines, ensuring that each job is completed before its deadline. Importantly,
each job takes exactly one unit of time to complete, and only one job can be scheduled at a
time. (Job Sequencing problem)

OBJECTIVE:
To schedule a set of jobs, each with a deadline and a profit, such that the total profit is
maximized. Each job takes exactly one unit of time, and only one job can be scheduled at
any given time. A job must be completed on or before its deadline.

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

struct Job {
char id[5];
int deadline;
int profit;
};
int compare(const void* a, const void* b) {
return ((struct Job*)b)->profit - ((struct Job*)a)->profit;
}.
3
int min(int a, int b) {
return (a < b) ? a : b;
}
int main() {
int n;
printf("Enter number of jobs: ");
scanf("%d", &n);

struct Job jobs[n];


printf("Enter job id, deadline, and profit for each job:\n");
for (int i = 0; i < n; i++) {
printf("Job %d:\n", i + 1);
printf(" ID: ");
scanf("%s", jobs[i].id);
printf(" Deadline: ");
scanf("%d", &jobs[i].deadline);
printf(" Profit: ");
scanf("%d", &jobs[i].profit);
}

qsort(jobs, n, sizeof(struct Job), compare);

int maxDeadline = 0;
for (int i = 0; i < n; i++) {
if (jobs[i].deadline > maxDeadline)
maxDeadline = jobs[i].deadline;
}
int slots[maxDeadline];
for (int i = 0; i < maxDeadline; i++)
slots[i] = -1;

int totalProfit = 0;
printf("\nScheduled Jobs: ");
for (int i = 0; i < n; i++) {
for (int j = min(jobs[i].deadline, maxDeadline-) 1; j >= 0; j--) {
if (slots[j] == -1) {
slots[j] = i;
totalProfit += jobs[i].profit;
printf("%s ", jobs[i].id);
break;
}
}
}

printf("\nTotal Profit: %d\n", totalProfit);


return 0;
}

15.PROBLEM STATEMENT:
You are given a connected, undirected graph with weighted edges. The objective is to find a
Minimum Spanning Tree (MST) of the graph by Kruskal’s algorithm. An MST is a subset
of the edges that connects all the vertices together, without any cycles, and with the minimum
possible total edge weight. (Graph input as adjacency matrix)

OBJECTIVE:
To find the Minimum Spanning Tree (MST) of a connected, undirected, weighted graph
using Kruskal’s algorithm. An MST includes all vertices with the minimum total edge
weight and no cycles.

ALGORITHM:
CODE:
#include <stdio.h>
#include <stdlib.h>
#define MAX 100

struct Edge {
int src, dest, weight;
};
int compare(const void* a, const void* b) {
return ((struct Edge*)a)->weight - ((struct Edge*)b)->weight;
}
int find(int parent[], int i) {
if (parent[i] != i)
parent[i] = find(parent, parent[i]);
return parent[i];
}
void unionSet(int parent[], int rank[], int x, int y) {
int xroot = find(parent, x);
int yroot = find(parent, y);

if (rank[xroot] < rank[yroot])


parent[xroot] = yroot;
else if (rank[xroot] > rank[yroot])
parent[yroot] = xroot;
else {
parent[yroot] = xroot;
rank[xroot]++;
}
}

int main() {
int V;
int adj[MAX][MAX];
struct Edge edges[MAX * MAX];
int edgeCount = 0;

printf("Enter number of vertices: ");


scanf("%d", &V);
printf("Enter adjacency matrix (enter 0 if no edge):\n");
for (int i = 0; i < V; i++) {
for (int j = 0; j < V; j++) {
scanf("%d", &adj[i][j]);
if (j > i && adj[i][j] != 0) {
edges[edgeCount].src = i;
edges[edgeCount].dest = j;
edges[edgeCount].weight = adj[i][j];
edgeCount++;
}
}
}

qsort(edges, edgeCount, sizeof(struct Edge), compare);


int parent[V], rank[V];
for (int i = 0; i < V; i++) {
parent[i] = i;
rank[i] = 0;
}
printf("\nEdges in MST:\n");
int totalWeight = 0;
int edgesInMST = 0;

for (int i = 0; i < edgeCount && edgesInMST < V - 1; i++) {


int u = edges[i].src;
int v = edges[i].dest;
int setU = find(parent, u);
int setV = find(parent, v);

if (setU != setV) {
printf("%d - %d (Weight: %d)\n", u, v, edges[i].weight);
totalWeight += edges[i].weight;
unionSet(parent, rank, setU, setV);
edgesInMST++;
}
}
printf("Total weight of MST: %d\n", totalWeight);
return 0;
}
16.PROBLEM STATEMENT:
You are given a connected, undirected graph with weighted edges. The objective is to find a
Minimum Spanning Tree (MST) of the graph by Prim’s algorithm. An MST is a subset of
the edges that connects all the vertices together, without any cycles, and with the minimum
possible total edge weight. (Graph input as adjacency matrix)

OBJECTIVE:
To find the Minimum Spanning Tree (MST) of a connected, undirected, weighted graph
using Prim’s algorithm. The MST connects all the vertices with the minimum total edge
weight and no cycles, using a greedy approach that grows the MST one vertex at a time.

ALGORITHM:
CODE:
#include <stdio.h>
#include <limits.h>
#include <stdbool.h>
#define MAX 100

int findMinKey(int key[], bool visited[], int V) {


int min = INT_MAX, min_index;

for (int v = 0; v < V; v++)


if (!visited[v] && key[v] < min)
min = key[v], min_index = v;
return min_index;
}

void primMST(int graph[MAX][MAX], int V) {


int parent[V];
int key[V];
bool visited[V];

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


key[i] = INT_MAX;
visited[i] = false;
}
key[0] = 0;
parent[0] = -1;
for (int count = 0; count < V - 1; count++) {
int u = findMinKey(key, visited, V);
visited[u] = true;

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


if (graph[u][v] && !visited[v] && graph[u][v] < key[v]) {
parent[v] = u;
key[v] = graph[u][v];
}
}
}
int totalWeight = 0;
printf("Edges in MST:\n");
for (int i = 1; i < V; i++) {
printf("%d - %d (Weight: %d)\n", parent[i], i, graph[i][parent[i]]);
totalWeight += graph[i][parent[i]];
}
printf("Total weight of MST: %d\n", totalWeight);
}
int main() {
int V;
int graph[MAX][MAX];

printf("Enter number of vertices: ");


scanf("%d", &V);
printf("Enter adjacency matrix (0 if no edge):\n");
for (int i = 0; i < V; i++)
for (int j = 0; j < V; j++)
scanf("%d", &graph[i][j]);
primMST(graph, V);
return 0;
}

17.PROBLEM STATEMENT:
You are given a connected, weighted, and directed graph. The objective is to find the shortest
path from a specified source vertex to all other vertices in the graph. Write a program to solve
the shortest path problem using Dijkstra's Algorithm. Your program should compute and
print the shortest distances from the source vertex to all other vertices.

OBJECTIVE:
To find the shortest path from a given source vertex to all other vertices in a connected,
weighted, directed graph using Dijkstra’s algorithm. The goal is to minimize the total
edge weight from the source to each vertex.

ALGORITHM:
CODE:
#include <stdio.h>
#include <limits.h>
#include <stdbool.h>
#define MAX 100
#define INF 99999

int findMinDistance(int dist[], bool visited[], int V) {


int min = INF, min_index = -1;
for (int i = 0; i < V; i++) {
if (!visited[i] && dist[i] <= min) {
min = dist[i];
min_index = i;
}
}
return min_index;
}
void dijkstra(int graph[MAX][MAX], int V, int src) {
int dist[V];
bool visited[V];
for (int i = 0; i < V; i++) {
dist[i] = INF;
visited[i] = false;
}
dist[src] = 0;
for (int count = 0; count < V - 1; count++) {
int u = findMinDistance(dist, visited, V);
visited[u] = true;

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


if (!visited[v] && graph[u][v] && dist[u] != INF &&
dist[u] + graph[u][v] < dist[v]) {
dist[v] = dist[u] + graph[u][v];
}
}
}
printf("Vertex \t Distance from Source %d\n", src);
for (int i = 0; i < V; i++) {
printf("%d \t\t %d\n", i, dist[i]);
}
}
int main() {
int V, graph[MAX][MAX], source;

printf("Enter number of vertices: ");


scanf("%d", &V);

printf("Enter the adjacency matrix (0 for no edge):\n");


for (int i = 0; i < V; i++)
for (int j = 0; j < V; j++)
scanf("%d", &graph[i][j]);

printf("Enter the source vertex (0 to %d): ", V - 1);


scanf("%d", &source);
dijkstra(graph, V, source);

return 0;
}
18.PROBLEM STATEMENT:
You are given a connected, directed graph with weighted edges. The objective is to find the
shortest path from a specified source vertex to all other vertices in the graph. Write a program
to solve the single-source shortest path problem using Bellman-Ford Algorithm. Your
program should compute and print the shortest distances from the source vertex to all other
vertices and indicate whether the graph contains a negative-weight cycle.

OBJECTIVE:
To find the shortest path from a specified source vertex to all other vertices in a
connected, directed, weighted graph using the Bellman-Ford Algorithm. The algorithm
also detects if the graph contains a negative-weight cycle.

ALGORITHM:
CODE:
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#define INF 99999

struct Edge {
int src, dest, weight;
};
void bellmanFord(struct Edge edges[], int V, int E, int src) {
int dist[V];
for (int i = 0; i < V; i++)
dist[i] = INF;
dist[src] = 0;
for (int i = 1; i <= V - 1; i++) {
for (int j = 0; j < E; j++) {
int u = edges[j].src;
int v = edges[j].dest;
int w = edges[j].weight;

if (dist[u] != INF && dist[u] + w < dist[v]) {


dist[v] = dist[u] + w;
}
}
}
for (int j = 0; j < E; j++) {
int u = edges[j].src;
int v = edges[j].dest;
int w = edges[j].weight;

if (dist[u] != INF && dist[u] + w < dist[v]) {


printf("Graph contains a negative weight cycle.\n");
return;
}
}
printf("Vertex\tDistance from Source %d\n", src);
for (int i = 0; i < V; i++) {
if (dist[i] == INF)
printf("%d\tINF\n", i);
else
printf("%d\t%d\n", i, dist[i]);
}
}
int main() {
int V, E, src;
printf("Enter number of vertices: ");
scanf("%d", &V);
printf("Enter number of edges: ");
scanf("%d", &E);

struct Edge edges[E];


printf("Enter edges (src dest weight):\n");
for (int i = 0; i < E; i++) {
scanf("%d%d%d", &edges[i].src, &edges[i].dest, &edges[i].weight);
}
printf("Enter source vertex: ");
scanf("%d", &src);
bellmanFord(edges, V, E, src);
return 0;
}
19.PROBLEM STATEMENT:
You are given a connected, weighted, and directed graph. The objective is to find the shortest
paths between all pairs of vertices in the graph. Write a program to solve the all-pairs shortest
path problem using Floyd-Warshall Algorithm. Your program should compute and print the
shortest distances between all pairs of vertices.

OBJECTIVE:
To find the shortest paths between all pairs of vertices in a connected, directed, weighted
graph using the Floyd-Warshall Algorithm. The algorithm computes the shortest paths
between every pair of vertices by considering each vertex as an intermediate vertex, and
progressively improving the shortest path estimates.

ALGORITHM:
CODE:
#include <stdio.h>
#define MAX 100
#define INF 99999

void printSolution(int dist[][MAX], int V) {


printf("Shortest distances between every pair of vertices:\n");
for (int i = 0; i < V; i++) {
for (int j = 0; j < V; j++) {
if (dist[i][j] == INF)
printf("INF ");
else
printf("%3d ", dist[i][j]);
}
printf("\n");
}
}
void floydWarshall(int graph[][MAX], int V) {
int dist[MAX][MAX];
for (int i = 0; i < V; i++)
for (int j = 0; j < V; j++)
dist[i][j] = graph[i][j];

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


for (int i = 0; i < V; i++) {
for (int j = 0; j < V; j++) {
if (dist[i][k] != INF && dist[k][j] != INF &&
dist[i][j] > dist[i][k] + dist[k][j]) {
dist[i][j] = dist[i][k] + dist[k][j];
}
}
}
}
for (int i = 0; i < V; i++) {
if (dist[i][i] < 0) {
printf("Graph contains a negative weight cycle.\n");
return;
}
}
printSolution(dist, V);
}
int main() {
int V;
int graph[MAX][MAX];

printf("Enter number of vertices: ");


scanf("%d", &V);

printf("Enter the adjacency matrix (use 99999 for INF/no edge):\n");


for (int i = 0; i < V; i++)
for (int j = 0; j < V; j++)
scanf("%d", &graph[i][j]);

floydWarshall(graph, V);
return 0;
}

20.PROBLEM STATEMENT:
You are given a knapsack that can hold a total weight of W. You have a set of n items, each
with a weight wi and a value vi. Your goal is to determine the maximum total value you can
carry in your knapsack without exceeding its weight capacity. This is a classic example of the
0/1 Knapsack Problem, where each item can either be included or excluded from the
knapsack. Write a program to solve the 0/1 Knapsack Problem using Dynamic
Programming. Your program should compute and print the maximum total value that can be
obtained without exceeding the knapsack's weight capacity.

OBJECTIVE:
To find the maximum value that can be carried in a knapsack with a given weight capacity,
using a set of items, each with a weight and a value. The goal is to maximize the total value
without exceeding the knapsack's weight capacity, using the 0/1 Knapsack Problem
approach. We will solve this using Dynamic Programming.

ALGORITHM:
CODE:
#include <stdio.h>
#define MAX_ITEMS 100
#define MAX_WEIGHT 1000

int max(int a, int b) {


return (a > b) ? a : b;
}
int knapsack(int weights[], int values[], int n, int W) {
int dp[n + 1][W + 1];

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


for (int w = 0; w <= W; w++) {
if (i == 0 || w == 0)
dp[i][w] = 0;
else if (weights[i - 1] <= w)
dp[i][w] = max(values[i - 1] + dp[i - 1][w - weights[i - 1]], dp[i - 1][w]);
else
dp[i][w] = dp[i - 1][w];
}
}
return dp[n][W];
}

int main() {
int n, W;
int weights[MAX_ITEMS], values[MAX_ITEMS];

printf("Enter number of items: ");


scanf("%d", &n);

printf("Enter weights of items:\n");


for (int i = 0; i < n; i++)
scanf("%d", &weights[i]);
printf("Enter values of items:\n");

for (int i = 0; i < n; i++)


scanf("%d", &values[i]);
printf("Enter maximum capacity of knapsack: ");
scanf("%d", &W);

int maxValue = knapsack(weights, values, n, W);


printf("Maximum value in the knapsack = %d\n", maxValue);

return 0;
}
21.PROBLEM STATEMENT:
The 8 Queens Problem is a classic puzzle in chess and computer science. The objective is to
place eight queens on an 8×8 chessboard such that no two queens threaten each other. In
chess, a queen can attack another queen if they share the same row, column, or diagonal. The
challenge is to find all possible arrangements where no two queens can attack each other.
Write a program to solve the 8 Queens Problem using Backtracking. Your program should
compute and print all possible configurations where eight queens can be placed on the
chessboard without threatening each other.

OBJECTIVE:
The 8 Queens Problem is to place 8 queens on an 8x8 chessboard such that no two queens
threaten each other. A queen can attack another queen if they share the same row, column, or
diagonal. The goal is to find all possible configurations where no two queens can attack each
other using Backtracking.

ALGORITHM:
CODE:
#include <stdio.h>
#include <math.h>
#define SIZE 8

int board[SIZE];
int solutionCount = 0;
int isSafe(int row, int col) {
for (int i = 0; i < row; i++) {
if (board[i] == col || abs(board[i] - col) == abs(i - row))
return 0;
}
return 1;
}
void solve(int row) {
if (row == SIZE) {
solutionCount++;
printf("\nSolution %d:\n", solutionCount);
for (int i = 0; i < SIZE; i++) {
for (int j = 0; j < SIZE; j++) {
if (board[i] == j)
printf("Q ");
else
printf(". ");
}
printf("\n");
}
return;
}
for (int col = 0; col < SIZE; col++) {
if (isSafe(row, col)) {
board[row] = col;
solve(row + 1);
}
}
}
int main() {
solve(0);
printf("\nTotal number of solutions: %d\n", solutionCount);
return 0;
}

You might also like