Skip to content
This repository has been archived by the owner on Sep 27, 2020. It is now read-only.

Created Knapsack Problem #335

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
53 changes: 53 additions & 0 deletions Java/floyd_warshal.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
import java.lang.*;

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

private void floydWarshall(int[][] graph) {
int[][] dist = new int[V][V];
int i, j, k;

for (i = 0; i < V; i++)
for (j = 0; j < V; j++)
dist[i][j] = graph[i][j];

for (k = 0; k < V; k++) {
// Pick all vertices as source one by one
for (i = 0; i < V; i++) {
for (j = 0; j < V; 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);
}

private 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();
}
}

public static void main(String[] args) {
int[][] graph = {{0, 5, INF, 10},
{INF, 0, 3, INF},
{INF, INF, 0, 1},
{INF, INF, INF, 0}
};
AllPairShortestPath a = new AllPairShortestPath();

a.floydWarshall(graph);
}
}
30 changes: 30 additions & 0 deletions Python/0-1_Knapsack_Problem.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
''' Similar to fractional KnapSack except
you cannot break an item,
either pick the complete item,
or don’t pick it (0-1 property).'''

def maxKnapSack(W , wt , profit , n):

if n == 0 or W == 0 :
return 0

# If weight of item is more than capacity W
# then this item cannot be included in the optimal solution

if (wt[n-1] > W):
return maxKnapSack(W , wt , profit , n-1)

# return the maximum of two cases:
# (a) item included
# (b) not included
else:
return max(profit[n-1] + maxKnapSack(W-wt[n-1] , wt , profit , n-1),
maxKnapSack(W , wt , profit , n-1))

# Driver Program
if __name__ == '__main__':
profit = [60, 100, 120]
wt = [10, 20, 30]
W = 50
n = len(profit)
print(maxKnapSack(W , wt , profit , n))