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

DAA Lab Programs

1. The document discusses algorithms to solve sorting and knapsack problems using greedy and divide-and-conquer approaches in C++ and Java. It includes code for selection sort, quicksort, mergesort, and a greedy fractional knapsack algorithm. 2. For each algorithm, it provides pseudocode and asks to analyze time complexity, run programs for varied input sizes, and plot runtime versus problem size graphs. 3. The document compares worst case, average case, and best case time complexities for quicksort and mergesort.

Uploaded by

V Manjunath
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
56 views

DAA Lab Programs

1. The document discusses algorithms to solve sorting and knapsack problems using greedy and divide-and-conquer approaches in C++ and Java. It includes code for selection sort, quicksort, mergesort, and a greedy fractional knapsack algorithm. 2. For each algorithm, it provides pseudocode and asks to analyze time complexity, run programs for varied input sizes, and plot runtime versus problem size graphs. 3. The document compares worst case, average case, and best case time complexities for quicksort and mergesort.

Uploaded by

V Manjunath
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 26

DAA Lab 21CS42

1. Sort a given set of n integer elements using Selection Sort method and compute its time complexity. Run the
program for varied values of n> 5000 and record the time taken to sort. Plot a graph of the time taken versus
n. The elements can be read from a file or can be generated using the random number generator. Demonstrate
using C++/Java how the brute force method works along with its time complexity analysis: worst case,
average case and best case.
Selection sort in C++

#include <iostream>
using namespace std;
// function to swap the the position of two elements
void swap(int *a, int *b) {
int temp = *a;
*a = *b;
*b = temp;
}
// function to print an array
void printArray(int array[], int size) {
for (int i = 0; i < size; i++) {
cout << array[i] << " ";
}
cout << endl;
}
void selectionSort(int array[], int size) {
for (int step = 0; step < size - 1; step++) {
int min_idx = step;
for (int i = step + 1; i < size; i++) {
// To sort in descending order, change > to < in this line.
// Select the minimum element in each loop.
if (array[i] < array[min_idx])
min_idx = i;
}

Compiled Swapna T ,CSE-NITR,Raichur


// put min at the correct position
swap(&array[min_idx], &array[step]);
}
}
// driver code
int main() {
int data[] = {20, 12, 10, 15, 2};
int size = sizeof(data) / sizeof(data[0]);
selectionSort(data, size);
cout << "Sorted array in Acsending Order:\n";
printArray(data, size);
}
// Selection sort in Java

import java.util.Arrays;

class SelectionSort {
void selectionSort(int array[]) {
int size = array.length;

for (int step = 0; step < size - 1; step++) {


int min_idx = step;

for (int i = step + 1; i < size; i++) {

// To sort in descending order, change > to < in this line.


// Select the minimum element in each loop.
if (array[i] < array[min_idx]) {
min_idx = i;
}
}
Compiled Swapna T ,CSE-NITR,Raichur
// put min at the correct position
int temp = array[step];
array[step] = array[min_idx];
array[min_idx] = temp;
}
}

// driver code
public static void main(String args[]) {
int[] data = { 20, 12, 10, 15, 2 };
SelectionSort ss = new SelectionSort();
ss.selectionSort(data);
System.out.println("Sorted Array in Ascending Order: ");
System.out.println(Arrays.toString(data));
}
}

2. Sort a given set of n integer elements using Quick Sort method and compute its time complexity. Run the
program for varied values of n> 5000 and record the time taken to sort. Plot a graph of the time taken versus
n. The elements can be read from a file or can be generated using the random number generator. Demonstrate
using C++/Java how the divide-and-conquer method works along with its time complexity analysis: worst
case, average case and best case

import java.util.Random;

import java.util.Scanner;

class QuickSort {

static int comparisons = 0;

static int[] arr;

static void quickSort(int low, int high) {

if (low < high) {

Compiled Swapna T ,CSE-NITR,Raichur


comparisons += 1;

int j = partition(low, high);

quickSort(low, j - 1);

quickSort(j + 1, high);

static int partition(int low, int high) {

int pivot = arr[low];

int i = low, j = high;

while (i < j) {

comparisons += 1;

while (i < high && arr[i] <= pivot) {

comparisons += 2;

i = i + 1;

while (j > low && arr[j] >= pivot) {

comparisons += 2;

j = j - 1;

if (i < j) {

comparisons += 1;

interchange(i, j);

Compiled Swapna T ,CSE-NITR,Raichur


}

arr[low] = arr[j];

arr[j] = pivot;

return j;

static void interchange(int i, int j) {

int temp = arr[i];

arr[i] = arr[j];

arr[j] = temp;

public static void main(String[] args) {

int n;

Scanner scanner = new Scanner(System.in);

System.out.print("Enter value of n: ");

n = scanner.nextInt();

arr = new int[n];

System.out.println("Quick Sort");

System.out.println("1. Best/Average Case");

System.out.println("2. Worst Case");

int ch = scanner.nextInt();

switch (ch) {

case 1:

Random random = new Random(3000);

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


Compiled Swapna T ,CSE-NITR,Raichur
arr[i] = random.nextInt();

break;

case 2:

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

arr[i] = i + 1;

break;

long start = System.nanoTime();

quickSort(0, n - 1);

long end = System.nanoTime();

System.out.println("Sorted Array");

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

System.out.println(arr[i]);

System.out.println("Time taken: " + (end - start));

System.out.println("Comparisons: " + comparisons);

3. . Sort a given set of n integer elements using Merge Sort method and compute its time complexity. Run the
program for varied values of n> 5000, and record the time taken to sort. Plot a graph of the time taken versus
n. The elements can be read from a file or can be generated using the random number generator. Demonstrate
using C++/Java how the divide-and-conquer method works along with its time complexity analysis: worst
case, average case and best case.

Compiled Swapna T ,CSE-NITR,Raichur


import java.util.Random;

import java.util.Scanner;

public class MergeSort

public static void main(String[] args)

int a[]= new int[100000];

Scanner in = new Scanner(System.in);

long start, end;

System.out.print("Enter the number of elements to be sorted: ");

int n = in.nextInt();

Random rand= new Random();

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

a[i]=rand.nextInt(2000);

System.out.println("Array elements to be sorted are:");

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

System.out.println(a[i]);

start=System.nanoTime();

mergesort(a,0,n-1);

end=System.nanoTime();

System.out.println("\nThe sorted elements are: ");

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

System.out.println(a[i]);

System.out.println("\nThe time taken to sort is "+(end-start)+"ns");

static void mergesort(int a[], int low, int high)

Compiled Swapna T ,CSE-NITR,Raichur


int mid;

if(low < high)

mid = (low+high)/2;

mergesort(a, low, mid);

mergesort(a, mid+1, high);

merge(a, low, mid, high);

static void merge(int a[], int low, int mid, int high)

int i, j, h, k, b[]= new int[100000];

h=low; i=low; j=mid+1;

while((h<=mid) && (j<=high))

if(a[h] < a[j])

b[i]=a[h];

h=h+1;

else

b[i] = a[j];

j=j+1;

i = i+1;

Compiled Swapna T ,CSE-NITR,Raichur


if(h > mid)

for(k=j; k<=high; k++)

b[i]=a[k];

i= i+1;

else

for(k=h;k<=mid;k++)

b[i]=a[k];

i= i+1;

for(k=low; k<= high; k++)

a[k] = b[k];

4. To solve Knapsack problem using Greedy method


import java.lang.*;
import java.util.Arrays;
import java.util.Comparator;

// Greedy approach
public class FractionalKnapSack {

// Function to get maximum value


private static double getMaxValue(ItemValue[] arr,
int capacity)
{
// Sorting items by profit/weight ratio;
Compiled Swapna T ,CSE-NITR,Raichur
Arrays.sort(arr, new Comparator<ItemValue>() {
@Override
public int compare(ItemValue item1,
ItemValue item2)
{
double cpr1
= new Double((double)item1.profit
/ (double)item1.weight);
double cpr2
= new Double((double)item2.profit
/ (double)item2.weight);

if (cpr1 < cpr2)


return 1;
else
return -1;
}
});

double totalValue = 0d;

for (ItemValue i : arr) {

int curWt = (int)i.weight;


int curVal = (int)i.profit;

if (capacity - curWt >= 0) {

// This weight can be picked whole


capacity = capacity - curWt;
totalValue += curVal;
}
else {

// Item cant be picked whole


double fraction
= ((double)capacity / (double)curWt);
totalValue += (curVal * fraction);
capacity
= (int)(capacity - (curWt * fraction));
break;
}
}

return totalValue;
}

// Item value class


static class ItemValue {

int profit, weight;


Compiled Swapna T ,CSE-NITR,Raichur
// Item value function
public ItemValue(int val, int wt)
{
this.weight = wt;
this.profit = val;
}
}

// Driver code
public static void main(String[] args)
{

ItemValue[] arr = { new ItemValue(60, 10),


new ItemValue(100, 20),
new ItemValue(120, 30) };

int capacity = 50;

double maxValue = getMaxValue(arr, capacity);

// Function call
System.out.println(maxValue);
}
}

5. To find shortest paths to other vertices from a given vertex in a weighted connected graph, using Dijkstra's
algorithm
// A Java program for Dijkstra's single source shortest path
// algorithm. The program is for adjacency matrix
// representation of the graph
import java.io.*;
import java.lang.*;
import java.util.*;

class ShortestPath {
// A utility function to find the vertex with minimum
// distance value, from the set of vertices not yet
// included in shortest path tree
static final int V = 9;
int minDistance(int dist[], Boolean sptSet[])
{
// Initialize min value
int min = Integer.MAX_VALUE, min_index = -1;

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


if (sptSet[v] == false && dist[v] <= min) {
min = dist[v];
min_index = v;
}
Compiled Swapna T ,CSE-NITR,Raichur
return min_index;
}

// A utility function to print the constructed distance


// array
void printSolution(int dist[])
{
System.out.println(
"Vertex \t\t Distance from Source");
for (int i = 0; i < V; i++)
System.out.println(i + " \t\t " + dist[i]);
}

// Function that implements Dijkstra's single source


// shortest path algorithm for a graph represented using
// adjacency matrix representation
void dijkstra(int graph[][], int src)
{
int dist[] = new int[V]; // The output array.
// dist[i] will hold
// the shortest distance from src to i

// sptSet[i] will true if vertex i is included in


// shortest path tree or shortest distance from src
// to i is finalized
Boolean sptSet[] = new Boolean[V];

// Initialize all distances as INFINITE and stpSet[]


// as false
for (int i = 0; i < V; i++) {
dist[i] = Integer.MAX_VALUE;
sptSet[i] = false;
}

// Distance of source vertex from itself is always 0


dist[src] = 0;

// Find shortest path for all vertices


for (int count = 0; count < V - 1; count++) {
// Pick the minimum distance vertex from the set
// of vertices not yet processed. u is always
// equal to src in first iteration.
int u = minDistance(dist, sptSet);

// Mark the picked vertex as processed


sptSet[u] = true;

// Update dist value of the adjacent vertices of


// the picked vertex.
for (int v = 0; v < V; v++)
Compiled Swapna T ,CSE-NITR,Raichur
// Update dist[v] only if is not in sptSet,
// there is an edge from u to v, and total
// weight of path from src to v through u is
// smaller than current value of dist[v]
if (!sptSet[v] && graph[u][v] != 0
&& dist[u] != Integer.MAX_VALUE
&& dist[u] + graph[u][v] < dist[v])
dist[v] = dist[u] + graph[u][v];
}

// print the constructed distance array


printSolution(dist);
}

// Driver's code
public static void main(String[] args)
{
/* Let us create the example graph discussed above
*/
int graph[][]
= new int[][] { { 0, 4, 0, 0, 0, 0, 0, 8, 0 },
{ 4, 0, 8, 0, 0, 0, 0, 11, 0 },
{ 0, 8, 0, 7, 0, 4, 0, 0, 2 },
{ 0, 0, 7, 0, 9, 14, 0, 0, 0 },
{ 0, 0, 0, 9, 0, 10, 0, 0, 0 },
{ 0, 0, 4, 14, 10, 0, 2, 0, 0 },
{ 0, 0, 0, 0, 0, 2, 0, 1, 6 },
{ 8, 11, 0, 0, 0, 0, 1, 0, 7 },
{ 0, 0, 2, 0, 0, 0, 6, 7, 0 } };
ShortestPath t = new ShortestPath();

// Function call
t.dijkstra(graph, 0);
}
}

6. To find Minimum Cost Spanning Tree of a given connected undirected graph using Kruskal's algorithm. Use
Union-Find algorithms in your program.
Time Complexity: O(E * logE) or O(E * logV)
/ Java program for Kruskal's algorithm

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

public class KruskalsMST {

// Defines edge structure


static class Edge {
int src, dest, weight;
Compiled Swapna T ,CSE-NITR,Raichur
public Edge(int src, int dest, int weight)
{
this.src = src;
this.dest = dest;
this.weight = weight;
}
}

// Defines subset element structure


static class Subset {
int parent, rank;

public Subset(int parent, int rank)


{
this.parent = parent;
this.rank = rank;
}
}

// Starting point of program execution


public static void main(String[] args)
{
int V = 4;
List<Edge> graphEdges = new ArrayList<Edge>(
List.of(new Edge(0, 1, 10), new Edge(0, 2, 6),
new Edge(0, 3, 5), new Edge(1, 3, 15),
new Edge(2, 3, 4)));

// Sort the edges in non-decreasing order


// (increasing with repetition allowed)
graphEdges.sort(new Comparator<Edge>() {
@Override public int compare(Edge o1, Edge o2)
{
return o1.weight - o2.weight;
}
});

kruskals(V, graphEdges);
}

// Function to find the MST


private static void kruskals(int V, List<Edge> edges)
{
int j = 0;
int noOfEdges = 0;

// Allocate memory for creating V subsets


Subset subsets[] = new Subset[V];

// Allocate memory for results


Compiled Swapna T ,CSE-NITR,Raichur
Edge results[] = new Edge[V];

// Create V subsets with single elements


for (int i = 0; i < V; i++) {
subsets[i] = new Subset(i, 0);
}

// Number of edges to be taken is equal to V-1


while (noOfEdges < V - 1) {

// Pick the smallest edge. And increment


// the index for next iteration
Edge nextEdge = edges.get(j);
int x = findRoot(subsets, nextEdge.src);
int y = findRoot(subsets, nextEdge.dest);

// If including this edge doesn't cause cycle,


// include it in result and increment the index
// of result for next edge
if (x != y) {
results[noOfEdges] = nextEdge;
union(subsets, x, y);
noOfEdges++;
}

j++;
}

// Print the contents of result[] to display the


// built MST
System.out.println(
"Following are the edges of the constructed MST:");
int minCost = 0;
for (int i = 0; i < noOfEdges; i++) {
System.out.println(results[i].src + " -- "
+ results[i].dest + " == "
+ results[i].weight);
minCost += results[i].weight;
}
System.out.println("Total cost of MST: " + minCost);
}

// Function to unite two disjoint sets


private static void union(Subset[] subsets, int x,
int y)
{
int rootX = findRoot(subsets, x);
int rootY = findRoot(subsets, y);

if (subsets[rootY].rank < subsets[rootX].rank) {


subsets[rootY].parent = rootX;
Compiled Swapna T ,CSE-NITR,Raichur
}
else if (subsets[rootX].rank
< subsets[rootY].rank) {
subsets[rootX].parent = rootY;
}
else {
subsets[rootY].parent = rootX;
subsets[rootX].rank++;
}
}

// Function to find parent of a set


private static int findRoot(Subset[] subsets, int i)
{
if (subsets[i].parent == i)
return subsets[i].parent;

subsets[i].parent
= findRoot(subsets, subsets[i].parent);
return subsets[i].parent;
}
}
7. To find Minimum Cost Spanning Tree of a given connected undirected graph using Prim's algorithm.
/ A Java program for Prim's Minimum Spanning Tree (MST)
// algorithm. The program is for adjacency matrix
// representation of the graph

import java.io.*;
import java.lang.*;
import java.util.*;

class MST {

// Number of vertices in the graph


private static final int V = 5;

// A utility function to find the vertex with minimum


// key value, from the set of vertices not yet included
// in MST
int minKey(int key[], Boolean mstSet[])
{
// Initialize min value
int min = Integer.MAX_VALUE, min_index = -1;

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


if (mstSet[v] == false && key[v] < min) {
min = key[v];
min_index = v;
}

return min_index;
Compiled Swapna T ,CSE-NITR,Raichur
}

// A utility function to print the constructed MST


// stored in parent[]
void printMST(int parent[], int graph[][])
{
System.out.println("Edge \tWeight");
for (int i = 1; i < V; i++)
System.out.println(parent[i] + " - " + i + "\t"
+ graph[i][parent[i]]);
}

// Function to construct and print MST for a graph


// represented using adjacency matrix representation
void primMST(int graph[][])
{
// Array to store constructed MST
int parent[] = new int[V];

// Key values used to pick minimum weight edge in


// cut
int key[] = new int[V];

// To represent set of vertices included in MST


Boolean mstSet[] = new Boolean[V];

// Initialize all keys as INFINITE


for (int i = 0; i < V; i++) {
key[i] = Integer.MAX_VALUE;
mstSet[i] = false;
}

// Always include first 1st vertex in MST.


// Make key 0 so that this vertex is
// picked as first vertex
key[0] = 0;

// First node is always root of MST


parent[0] = -1;

// The MST will have V vertices


for (int count = 0; count < V - 1; count++) {

// Pick the minimum key vertex from the set of


// vertices not yet included in MST
int u = minKey(key, mstSet);

// Add the picked vertex to the MST Set


mstSet[u] = true;

// Update key value and parent index of the


Compiled Swapna T ,CSE-NITR,Raichur
// adjacent vertices of the picked vertex.
// Consider only those vertices which are not
// yet included in MST
for (int v = 0; v < V; v++)

// graph[u][v] is non zero only for adjacent


// vertices of m mstSet[v] is false for
// vertices not yet included in MST Update
// the key only if graph[u][v] is smaller
// than key[v]
if (graph[u][v] != 0 && mstSet[v] == false
&& graph[u][v] < key[v]) {
parent[v] = u;
key[v] = graph[u][v];
}
}

// Print the constructed MST


printMST(parent, graph);
}

public static void main(String[] args)


{
MST t = new MST();
int graph[][] = new int[][] { { 0, 2, 0, 6, 0 },
{ 2, 0, 3, 8, 5 },
{ 0, 3, 0, 0, 7 },
{ 6, 8, 0, 0, 9 },
{ 0, 5, 7, 9, 0 } };

// Print the solution


t.primMST(graph);
}
}

8. Solve All-Pairs Shortest Paths problem using Floyd's algorithm.


// Java program for Floyd Warshall All Pairs Shortest
// Path algorithm.
import java.io.*;
import java.lang.*;
import java.util.*;

class AllPairShortestPath {
final static int INF = 99999, V = 4;

void floydWarshall(int dist[][])


{

int i, j, k;

Compiled Swapna T ,CSE-NITR,Raichur


/* Add all vertices one by one
to the set of intermediate
vertices.
---> Before start of an iteration,
we have shortest
distances between all pairs
of vertices such that
the shortest distances consider
only the vertices in
set {0, 1, 2, .. k-1} as
intermediate vertices.
----> After the end of an iteration,
vertex no. k is added
to the set of intermediate
vertices and the set
becomes {0, 1, 2, .. k} */
for (k = 0; k < V; k++) {
// Pick all vertices as source one by one
for (i = 0; i < V; i++) {
// Pick all vertices as destination for the
// above picked source
for (j = 0; j < V; j++) {
// If vertex k is on the shortest path
// from i to j, then update the value of
// dist[i][j]
if (dist[i][k] + dist[k][j]
< dist[i][j])
dist[i][j]
= dist[i][k] + dist[k][j];
}
}
}

// Print the shortest distance matrix


printSolution(dist);
}

void printSolution(int dist[][])


{
System.out.println(
"The following matrix shows the shortest "
+ "distances between every pair of vertices");
for (int i = 0; i < V; ++i) {
for (int j = 0; j < V; ++j) {
if (dist[i][j] == INF)
System.out.print("INF ");
else
System.out.print(dist[i][j] + " ");
}
System.out.println();
}
Compiled Swapna T ,CSE-NITR,Raichur
}

// Driver's code
public static void main(String[] args)
{
/* Let us create the following weighted graph
10
(0)------->(3)
| /|\
5| |
| |1
\|/ |
(1)------->(2)
3 */
int graph[][] = { { 0, 5, INF, 10 },
{ INF, 0, 3, INF },
{ INF, INF, 0, 1 },
{ INF, INF, INF, 0 } };
AllPairShortestPath a = new AllPairShortestPath();

// Function call
a.floydWarshall(graph);
}
}

9. Solve Travelling Sales Person problem using Dynamic programming.


import java.io.*;
import java.util.*;

public class TSE {


// there are four nodes in example graph (graph is
// 1-based)
static int n = 4;
// give appropriate maximum to avoid overflow
static int MAX = 1000000;

// dist[i][j] represents shortest distance to go from i


// to j this matrix can be calculated for any given
// graph using all-pair shortest path algorithms
static int[][] dist = {
{ 0, 0, 0, 0, 0 }, { 0, 0, 10, 15, 20 },
{ 0, 10, 0, 25, 25 }, { 0, 15, 25, 0, 30 },
{ 0, 20, 25, 30, 0 },
};
// memoization for top down recursion

static int[][] memo = new int[n + 1][1 << (n + 1)];

static int fun(int i, int mask)


{
// base case
Compiled Swapna T ,CSE-NITR,Raichur
// if only ith bit and 1st bit is set in our mask,
// it implies we have visited all other nodes
// already
if (mask == ((1 << i) | 3))
return dist[1][i];
// memoization
if (memo[i][mask] != 0)
return memo[i][mask];

int res = MAX; // result of this sub-problem


// we have to travel all nodes j in mask and end the
// path at ith node so for every node j in mask,
// recursively calculate cost of travelling all
// nodes in mask
// except i and then travel back from node j to node
// i taking the shortest path take the minimum of
// all possible j nodes

for (int j = 1; j <= n; j++)


if ((mask & (1 << j)) != 0 && j != i && j != 1)
res = Math.min(res,
fun(j, mask & (~(1 << i)))
+ dist[j][i]);
return memo[i][mask] = res;
}

// Driver program to test above logic


public static void main(String[] args)
{
int ans = MAX;
for (int i = 1; i <= n; i++)
// try to go from node 1 visiting all nodes in
// between to i then return from i taking the
// shortest route to 1
ans = Math.min(ans, fun(i, (1 << (n + 1)) - 1)
+ dist[i][1]);

System.out.println(
"The cost of most efficient tour = " + ans);
}
}

10. Solve 0/1 Knapsack problem using Dynamic Programming method.


/* A Naive recursive implementation
of 0-1 Knapsack problem */
class Knapsack {

// A utility function that returns


// maximum of two integers
static int max(int a, int b) { return (a > b) ? a : b; }

Compiled Swapna T ,CSE-NITR,Raichur


// Returns the maximum value that
// can be put in a knapsack of
// capacity W
static int knapSack(int W, int wt[], int val[], int n)
{
// Base Case
if (n == 0 || W == 0)
return 0;

// If weight of the nth item is


// more than Knapsack capacity W,
// then this item cannot be included
// in the optimal solution
if (wt[n - 1] > W)
return knapSack(W, wt, val, n - 1);

// Return the maximum of two cases:


// (1) nth item included
// (2) not included
else
return max(val[n - 1]
+ knapSack(W - wt[n - 1], wt,
val, n - 1),
knapSack(W, wt, val, n - 1));
}

// Driver code
public static void main(String args[])
{
int profit[] = new int[] { 60, 100, 120 };
int weight[] = new int[] { 10, 20, 30 };
int W = 50;
int n = profit.length;
System.out.println(knapSack(W, weight, profit, n));
}
}

11. Design and implement C++/Java Program to find a subset of a given set S = {Sl, S2,…, Sn} of n
positive integers whose SUM is equal to a given positive integer d. For example, if S = {1, 2, 5, 6, 8}
and d= 9, there are two solutions {1, 2, 6} and {1, 8}. Display a suitable message, if the given problem
instance doesn't have a solution.

// A recursive solution for subset sum

import java.io.*;
class GFG {

// Returns true if there is a subset


// of set[] with sum equal to given sum
static boolean isSubsetSum(int set[], int n, int sum)
Compiled Swapna T ,CSE-NITR,Raichur
{
// Base Cases
if (sum == 0)
return true;
if (n == 0)
return false;

// If last element is greater than


// sum, then ignore it
if (set[n - 1] > sum)
return isSubsetSum(set, n - 1, sum);

// Else, check if sum can be obtained


// by any of the following
// (a) including the last element
// (b) excluding the last element
return isSubsetSum(set, n - 1, sum)
|| isSubsetSum(set, n - 1, sum - set[n - 1]);
}

// Driver code
public static void main(String args[])
{
int set[] = { 1, 2, 5, 6, 8};
int sum = 9;
int n = set.length;
if (isSubsetSum(set, n, sum) == true)
System.out.println("Found a subset"
+ " with given sum");
else
System.out.println("No subset with"
+ " given sum");
}
}

12. Design and implement C++/Java Program to find all Hamiltonian Cycles in a connected undirected
Graph G of n vertices using backtracking principle.

/* Java program for solution of Hamiltonian Cycle problem


using backtracking */
class HamiltonianCycle
{
final int V = 5;
int path[];

/* A utility function to check if the vertex v can be


added at index 'pos'in the Hamiltonian Cycle
constructed so far (stored in 'path[]') */
boolean isSafe(int v, int graph[][], int path[], int pos)
{
Compiled Swapna T ,CSE-NITR,Raichur
/* Check if this vertex is an adjacent vertex of
the previously added vertex. */
if (graph[path[pos - 1]][v] == 0)
return false;

/* Check if the vertex has already been included.


This step can be optimized by creating an array
of size V */
for (int i = 0; i < pos; i++)
if (path[i] == v)
return false;

return true;
}

/* A recursive utility function to solve hamiltonian


cycle problem */
boolean hamCycleUtil(int graph[][], int path[], int pos)
{
/* base case: If all vertices are included in
Hamiltonian Cycle */
if (pos == V)
{
// And if there is an edge from the last included
// vertex to the first vertex
if (graph[path[pos - 1]][path[0]] == 1)
return true;
else
return false;
}

// Try different vertices as a next candidate in


// Hamiltonian Cycle. We don't try for 0 as we
// included 0 as starting point in hamCycle()
for (int v = 1; v < V; v++)
{
/* Check if this vertex can be added to Hamiltonian
Cycle */
if (isSafe(v, graph, path, pos))
{
path[pos] = v;

/* recur to construct rest of the path */


if (hamCycleUtil(graph, path, pos + 1) == true)
return true;

/* If adding vertex v doesn't lead to a solution,


then remove it */
path[pos] = -1;
}
}
Compiled Swapna T ,CSE-NITR,Raichur
/* If no vertex can be added to Hamiltonian Cycle
constructed so far, then return false */
return false;
}

/* This function solves the Hamiltonian Cycle problem using


Backtracking. It mainly uses hamCycleUtil() to solve the
problem. It returns false if there is no Hamiltonian Cycle
possible, otherwise return true and prints the path.
Please note that there may be more than one solutions,
this function prints one of the feasible solutions. */
int hamCycle(int graph[][])
{
path = new int[V];
for (int i = 0; i < V; i++)
path[i] = -1;

/* Let us put vertex 0 as the first vertex in the path.


If there is a Hamiltonian Cycle, then the path can be
started from any point of the cycle as the graph is
undirected */
path[0] = 0;
if (hamCycleUtil(graph, path, 1) == false)
{
System.out.println("\nSolution does not exist");
return 0;
}

printSolution(path);
return 1;
}

/* A utility function to print solution */


void printSolution(int path[])
{
System.out.println("Solution Exists: Following" +
" is one Hamiltonian Cycle");
for (int i = 0; i < V; i++)
System.out.print(" " + path[i] + " ");

// Let us print the first vertex again to show the


// complete cycle
System.out.println(" " + path[0] + " ");
}

// driver program to test above function


public static void main(String args[])
{
HamiltonianCycle hamiltonian =
new HamiltonianCycle();
Compiled Swapna T ,CSE-NITR,Raichur
/* Let us create the following graph
(0)--(1)--(2)
| /\ |
| / \ |
|/ \|
(3)-------(4) */
int graph1[][] = {{0, 1, 0, 1, 0},
{1, 0, 1, 1, 1},
{0, 1, 0, 0, 1},
{1, 1, 0, 0, 1},
{0, 1, 1, 1, 0},
};

// Print the solution


hamiltonian.hamCycle(graph1);

/* Let us create the following graph


(0)--(1)--(2)
| /\ |
| / \ |
|/ \|
(3) (4) */
int graph2[][] = {{0, 1, 0, 1, 0},
{1, 0, 1, 1, 1},
{0, 1, 0, 0, 1},
{1, 1, 0, 0, 0},
{0, 1, 1, 0, 0},
};

// Print the solution


hamiltonian.hamCycle(graph2);
}
}

Compiled Swapna T ,CSE-NITR,Raichur

You might also like