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

Ada 345

The document contains code for implementing depth-first search (DFS) and breadth-first search (BFS) algorithms on a graph data structure. It defines a Graph class with methods to add edges between vertices and perform DFS and BFS traversals. In main, it creates a graph with vertices and edges, and runs DFS and BFS on it, printing the traversal order. It also includes code for greedy algorithms like knapsack problem, activity selection, job scheduling, and minimum spanning tree algorithms like Prim's and Kruskal's.

Uploaded by

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

Ada 345

The document contains code for implementing depth-first search (DFS) and breadth-first search (BFS) algorithms on a graph data structure. It defines a Graph class with methods to add edges between vertices and perform DFS and BFS traversals. In main, it creates a graph with vertices and edges, and runs DFS and BFS on it, printing the traversal order. It also includes code for greedy algorithms like knapsack problem, activity selection, job scheduling, and minimum spanning tree algorithms like Prim's and Kruskal's.

Uploaded by

hello world
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 12

DFS

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

class Graph {
private int V; // No. of vertices

private LinkedList<Integer> adj[];

@SuppressWarnings("unchecked") Graph(int v)
{
V = v;
adj = new LinkedList[v];
for (int i = 0; i < v; ++i)
adj[i] = new LinkedList();
}

void addEdge(int v, int w)


{
adj[v].add(w); // Add w to v's list.
}

void DFSUtil(int v, boolean visited[])


{

visited[v] = true;
System.out.print(v + " ");

Iterator<Integer> i = adj[v].listIterator();
while (i.hasNext()) {
int n = i.next();
if (!visited[n])
DFSUtil(n, visited);
}
}

void DFS(int v)
{

boolean visited[] = new boolean[V];

DFSUtil(v, visited);
}

public static void main(String args[])


{
Graph g = new Graph(4);

g.addEdge(0, 1);
g.addEdge(0, 2);
g.addEdge(1, 2);
g.addEdge(2, 0);
g.addEdge(2, 3);
g.addEdge(3, 3);

System.out.println(
"Following is Depth First Traversal "
+ "(starting from vertex 2)");

g.DFS(2);
}
}

-----------------------------------------------------------------------------------
---------------------
BFS
-----------------------------------------------------------------------------------
----------------------
import java.io.*;
import java.util.*;

class Graph
{
private int V; // No. of vertices
private LinkedList<Integer> adj[]; //Adjacency Lists

Graph(int v)
{
V = v;
adj = new LinkedList[v];
for (int i=0; i<v; ++i)
adj[i] = new LinkedList();
}

void addEdge(int v,int w)


{
adj[v].add(w);
}

void BFS(int s)
{

boolean visited[] = new boolean[V];

LinkedList<Integer> queue = new LinkedList<Integer>();

visited[s]=true;
queue.add(s);

while (queue.size() != 0)
{
s = queue.poll();
System.out.print(s+" ");

Iterator<Integer> i = adj[s].listIterator();
while (i.hasNext())
{
int n = i.next();
if (!visited[n])
{
visited[n] = true;
queue.add(n);
}
}
}
}

public static void main(String args[])


{
Graph g = new Graph(4);

g.addEdge(0, 1);
g.addEdge(0, 2);
g.addEdge(1, 2);
g.addEdge(2, 0);
g.addEdge(2, 3);
g.addEdge(3, 3);

System.out.println("Following is Breadth First Traversal "+


"(starting from vertex 2)");

g.BFS(2);
}
}
-----------------------------------------------------------------------------------
-----
3.1
-----------------------------------------------
import java.util.*;
public class greedyknapsack{
public static void main(String args[]){
Scanner sc= new Scanner(System.in);
Random rd = new Random();
System.out.println("Enter number of pairs");
int n = sc.nextInt();
System.out.println("Enter value and weights of each item:");
int[] v= new int[n];
int[] w= new int[n];
float[] r= new float[n];
for(int i=0;i<n;i++){
v[i]=sc.nextInt();
w[i]=sc.nextInt();
r[i]=(float)v[i]/w[i];
}
System.out.println("Enter total weight of bag:");
int weight=sc.nextInt();
int max=0,value=0;
long start= System.nanoTime();
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
if(r[j]>r[max]){
max= j;
}
}
if(weight>0){
if(weight/w[max]<1){
value += (v[max]*weight)/w[max];
w[max] -= (w[max]-weight);
weight=0;
}
else{
value += v[max];
weight-=w[max];
}
}
else{
break;
}
r[max]=0;
max=0;
}
long end = System.nanoTime();
long runningtime = (end - start)/1000;
System.out.println("Maximum value of Knapsack Is: "+value+" & running time is:
"+runningtime+" microseconds");
}
}
-------------------------------------------------------
3.2
----------------------------------------------------------
import java.util.*;
public class greedyactivityselection {
public static void main(String args[]){
Scanner sc= new Scanner(System.in);
System.out.println("Enter Number of activity you want to perform: ");
int n = sc.nextInt();
int[] start = new int[n];
int[] end = new int[n];
System.out.println("Enter starting and ending time of each job:");
for(int i=0;i<n;i++){
start[i]=sc.nextInt();
end[i]=sc.nextInt();
}
for(int i=0;i<n;i++){
for(int j=i;j<n;j++){
if(end[j]<end[i]){
int temp = end[j];
end[j] = end[i];
end[i] = temp;
temp = start[j];
start[j] = start[i];
start[i] = temp;
}
else if(end[j]==end[i]&& start[j]<start[i]){
int temp = end[j];
end[j] = end[i];
end[i] = temp;
temp = start[j];
start[j] = start[i];
start[i] = temp;
}
}
}
int[] selected = new int[n];
selected[0]=1;
int j=0,p=1;
for(int i=1;i<n;i++){
if(start[i]>=end[j]){
selected[p]=i+1;
++p;
j=i;
}
}
System.out.println("Selected activities are:");
for(int i=0;selected[i]!=0;i++){
System.out.print(selected[i]+" ");
}
}
}
----------------------------------------------------------------------------
3.3
-----------------------------------------------------------------------------------
import java.util.*;
public class greedyjobscheduling {
public static void main(String args[]){
Scanner sc= new Scanner(System.in);
System.out.println("Enter Number of job: ");
int n =sc.nextInt();
System.out.println("Enter choice:\n Profit - 0\n loss - 1 ");
int choice = sc.nextInt();
int[][] job = new int[n][3];
//first=profit, second = deadline, third = name
System.out.println("Enter Profite/Penalty and deadline for each Job:");
for(int i=0;i<n;i++){
job[i][0]=sc.nextInt();
job[i][1]=sc.nextInt();
job[i][2]=i+1;
}
sortbyColumn(job, 0);
/* for(int i=0;i<n;i++){
System.out.print(job[i][0]+" "+job[i][1]+" "+job[i][2]+"\n");
}*/
int[][] selected = new int[n][3];
int profit = 0;
//first = date, second = time, third = name
for(int i=0;i<n;i++){
selected[i][0]=i+1;
selected[i][1]=0;
selected[i][2]=0;
}
if(choice == 0){
for(int i=0;i<n/2;i++){
for(int j=0;j<3;j++){
int temp = job[i][j];
job[i][j]=job[n-i-1][j];
job[n-i-1][j]=temp;
}
}
for(int i=0;i<n;i++){
for(int j=job[i][1];j>0;j--){
if(selected[j][1]==0){
selected[j][1] = 1;
selected[j][2]=job[i][2];
profit+= job[i][0];
break;
}
}
}
System.out.println("Your maximum profit by this job scheduling is: "+profit);
}
else{
for(int i=0;i<n;i++){
for(int j=job[i][1];j>0;j--){
if(selected[j][1]==0){
selected[j][1] = 1;
selected[j][2]=job[i][2];
profit+= job[i][0];
break;
}
}
}
System.out.println("Your minimum penalty by this job scheduling is: "+profit);
}
/* for(int i=0;i<n;i++){
System.out.print(selected[i][0]+" "+selected[i][1]+" "+selected[i][2]+"\n");
}*/
}
public static void sortbyColumn(int arr[][], int col){
Arrays.sort(arr, new Comparator<int[]>() {
@Override
public int compare(final int[] entry1, final int[] entry2) {
if (entry1[col] > entry2[col])
return 1;
else
return -1;
}
});
}
}
-----------------------------------------------------------------------------------
---------------
3.4
-----------------------------------------------------------------------------------
--
import java.util.*;
import java.lang.*;
import java.io.*;
class primsalgo {
private static final int V = 5;
int minKey(int key[], Boolean mstSet[])
{
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;
}
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]]);
}
void primMST(int graph[][])
{
int parent[] = new int[V];
int key[] = new int[V];
Boolean mstSet[] = new Boolean[V];
for (int i = 0; i < V; i++) {
key[i] = Integer.MAX_VALUE;
mstSet[i] = false;
}
key[0] = 0;
parent[0] = -1;
for (int count = 0; count < V - 1; count++) {
int u = minKey(key, mstSet);
mstSet[u] = true;
for (int v = 0; v < V; v++){
if (graph[u][v] != 0 && mstSet[v] == false && graph[u][v]

< key[v]) {

parent[v] = u;
key[v] = graph[u][v];
}

}
}
printMST(parent, graph);
}
public static void main(String[] args)
{
Scanner sc= new Scanner(System.in);
System.out.println("Enter number of nodes:");
int n = sc.nextInt();
int[][] a= new int[n+1][n+1];
System.out.println("Enter path values in following manner:");
System.out.print("a b c . . .\nb 1 2\nc 2 3\n.\n.\n.\n");
for(int i=0;i<n+1;i++){
a[0][i]=(i+1);
a[i][0]=(i+1);
}
for(int i=1;i<n+1;i++){
for(int j=1;j<n+1;j++){
a[i][j]=sc.nextInt();
}
}

primMST(a);
}
}
-----------------------------------------------------------------------------
3.5
-----------------------------------------------------------------------------------
----
import java.util.*;
import java.lang.*;
import java.io.*;
class kruskalsalgo {
class Edge implements Comparable<Edge>
{
int src, dest, weight;
public int compareTo(Edge compareEdge)
{
return this.weight - compareEdge.weight;
}
};
class subset
{
int parent, rank;
};
int V, E;
Edge edge[];
kruskalsalgo(int v, int e)
{
V = v;
E = e;
edge = new Edge[E];
for (int i = 0; i < e; ++i)
edge[i] = new Edge();

}
int find(subset subsets[], int i)
{
if (subsets[i].parent != i)
subsets[i].parent
= find(subsets, subsets[i].parent);

return subsets[i].parent;
}
void Union(subset subsets[], int x, int y)
{
int xroot = find(subsets, x);
int yroot = find(subsets, y);
if (subsets[xroot].rank
< subsets[yroot].rank)
subsets[xroot].parent = yroot;
else if (subsets[xroot].rank
> subsets[yroot].rank)
subsets[yroot].parent = xroot;
else {
subsets[yroot].parent = xroot;
subsets[xroot].rank++;
}
}
void KruskalMST()
{
Edge result[] = new Edge[V];
int e = 0;
int i = 0;
for (i = 0; i < V; ++i)
result[i] = new Edge();
Arrays.sort(edge);
subset subsets[] = new subset[V];
for (i = 0; i < V; ++i)
subsets[i] = new subset();
for (int v = 0; v < V; ++v)
{
subsets[v].parent = v;
subsets[v].rank = 0;
}
i = 0;
while (e < V - 1)
{
Edge next_edge = edge[i++];
int x = find(subsets, next_edge.src);
int y = find(subsets, next_edge.dest);
if (x != y) {
result[e++] = next_edge;
Union(subsets, x, y);
}
}
System.out.println("Following are the edges in "
+ "the constructed MST");

int minimumCost = 0;
for (i = 0; i < e; ++i)
{
System.out.println(result[i].src + " -- "
+ result[i].dest
+ " == " + result[i].weight);

minimumCost += result[i].weight;
}
System.out.println("Minimum Cost Spanning Tree "
+ minimumCost);

}
public static void main(String[] args)
{
int V = 4;
int E = 5;
kruskalsalgo graph = new kruskalsalgo(V, E);
graph.edge[0].src = 0;
graph.edge[0].dest = 1;
graph.edge[0].weight = 10;
graph.edge[1].src = 0;
graph.edge[1].dest = 2;
graph.edge[1].weight = 6;
graph.edge[2].src = 0;
graph.edge[2].dest = 3;
graph.edge[2].weight = 5;
graph.edge[3].src = 1;
graph.edge[3].dest = 3;
graph.edge[3].weight = 15;
graph.edge[4].src = 2;
graph.edge[4].dest = 3;
graph.edge[4].weight = 4;
graph.KruskalMST();
}
}
-----------------------------------------------------------------------------------
-------
4.1
==========================================================================
import java.io.*;
class makingchangedp
{
static int minCoins(int coins[], int m, int V)
{
int table[] = new int[V + 1];
table[0] = 0;
for (int i = 1; i <= V; i++)
table[i] = Integer.MAX_VALUE;
for (int i = 1; i <= V; i++)
{
for (int j = 0; j < m; j++)
if (coins[j] <= i)
{
int sub_res = table[i - coins[j]];
if (sub_res != Integer.MAX_VALUE
&& sub_res + 1 < table[i])
table[i] = sub_res + 1;
}
}
if(table[V]==Integer.MAX_VALUE)
return -1;
return table[V];
}
public static void main (String[] args)
{
int coins[] = {9, 6, 5, 1};
int m = coins.length;
int V = 11;
System.out.println ( "Minimum coins required is "+ minCoins(coins, m,
V));
}
}
===================================================================================
=============
4.2
====----------------------------------
===================================---------------------------
class 01knapsackdp{
static int max(int a, int b)
{
return (a > b) ? a : b;
}
static int knapSackRec(int W, int wt[],int val[], int n,int [][]dp)
{

if (n == 0 || W == 0)
return 0;

if (dp[n][W] != -1)
return dp[n][W];

if (wt[n - 1] > W)
return dp[n][W] = knapSackRec(W, wt, val,n - 1, dp);

else
return dp[n][W] = max((val[n - 1] +knapSackRec(W - wt[n - 1], wt,val, n - 1,
dp)),knapSackRec(W, wt, val,n - 1, dp));
}

static int knapSack(int W, int wt[], int val[], int N)


{
int dp[][] = new int[N + 1][W + 1];
for(int i = 0; i < N + 1; i++)
for(int j = 0; j < W + 1; j++)
dp[i][j] = -1;

return knapSackRec(W, wt, val, N, dp);


}
public static void main(String [] args)
{
int val[] = { 60, 100, 120 };
int wt[] = { 10, 20, 30 };

int W = 50;
int N = val.length;

System.out.println(knapSack(W, wt, val, N));


}
}
===================================================================================
=================
4.3
===================================================================================
=========
public class longestcommonsubsequence
{
int lcs( char[] X, char[] Y, int m, int n )
{
int L[][] = new int[m+1][n+1];
for (int i=0; i<=m; i++)
{
for (int j=0; j<=n; j++)
{
if (i == 0 || j == 0)
L[i][j] = 0;
else if (X[i-1] == Y[j-1])
L[i][j] = L[i-1][j-1] + 1;
else
L[i][j] = max(L[i-1][j], L[i][j-1]);
}
}
return L[m][n];
}
int max(int a, int b)
{
return (a > b)? a : b;
}
public static void main(String[] args)
{
longestcommonsubsequence lcs = new longestcommonsubsequence();
String s1 = "AGGTAB";
String s2 = "GXTXAYB";
char[] X=s1.toCharArray();
char[] Y=s2.toCharArray();
int m = X.length;
int n = Y.length;
System.out.println("Length of LCS is" + " " +lcs.lcs( X, Y, m, n ) );
}
}
===================================================================================
===================================
4.4
===================================================================================
====================================
import java.io.*;
import java.util.*;
class chainedmatrixmultiplication
{
static int[][] dp = new int[100][100];
static int matrixChainMemoised(int[] p, int i, int j)
{
if (i == j)
{
return 0;
}
if (dp[i][j] != -1)
{
return dp[i][j];
}
dp[i][j] = Integer.MAX_VALUE;
for (int k = i; k < j; k++)
{
dp[i][j] = Math.min(
dp[i][j], matrixChainMemoised(p, i, k)
+ matrixChainMemoised(p, k + 1, j)
+ p[i - 1] * p[k] * p[j]);
}
return dp[i][j];
}
static int MatrixChainOrder(int[] p, int n)
{
int i = 1, j = n - 1;
return matrixChainMemoised(p, i, j);
}
public static void main (String[] args)
{
int arr[] = { 1, 2, 3, 4 };
int n= arr.length;
for (int[] row : dp)
Arrays.fill(row, -1);
System.out.println("Minimum number of multiplications is " +
MatrixChainOrder(arr, n));
}
}
===================================================================================
========================================================

You might also like