Skip to content

Commit a0881cf

Browse files
committed
Initial
1 parent 75dbacb commit a0881cf

File tree

7 files changed

+516
-0
lines changed

7 files changed

+516
-0
lines changed
+90
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,90 @@
1+
# Python3 program to solve N Queen
2+
# Problem using backtracking
3+
global N
4+
N = 4
5+
6+
def printSolution(board):
7+
for i in range(N):
8+
for j in range(N):
9+
print (board[i][j], end = " ")
10+
print()
11+
12+
# A utility function to check if a queen can
13+
# be placed on board[row][col]. Note that this
14+
# function is called when "col" queens are
15+
# already placed in columns from 0 to col -1.
16+
# So we need to check only left side for
17+
# attacking queens
18+
def isSafe(board, row, col):
19+
20+
# Check this row on left side
21+
for i in range(col):
22+
if board[row][i] == 1:
23+
return False
24+
25+
# Check upper diagonal on left side
26+
for i, j in zip(range(row, -1, -1),
27+
range(col, -1, -1)):
28+
if board[i][j] == 1:
29+
return False
30+
31+
# Check lower diagonal on left side
32+
for i, j in zip(range(row, N, 1),
33+
range(col, -1, -1)):
34+
if board[i][j] == 1:
35+
return False
36+
37+
return True
38+
39+
def solveNQUtil(board, col):
40+
41+
# base case: If all queens are placed
42+
# then return true
43+
if col >= N:
44+
return True
45+
46+
# Consider this column and try placing
47+
# this queen in all rows one by one
48+
for i in range(N):
49+
50+
if isSafe(board, i, col):
51+
52+
# Place this queen in board[i][col]
53+
board[i][col] = 1
54+
55+
# recur to place rest of the queens
56+
if solveNQUtil(board, col + 1) == True:
57+
return True
58+
59+
# If placing queen in board[i][col
60+
# doesn't lead to a solution, then
61+
# queen from board[i][col]
62+
board[i][col] = 0
63+
64+
# if the queen can not be placed in any row in
65+
# this colum col then return false
66+
return False
67+
68+
# This function solves the N Queen problem using
69+
# Backtracking. It mainly uses solveNQUtil() to
70+
# solve the problem. It returns false if queens
71+
# cannot be placed, otherwise return true and
72+
# placement of queens in the form of 1s.
73+
# note that there may be more than one
74+
# solutions, this function prints one of the
75+
# feasible solutions.
76+
def solveNQ():
77+
board = [ [0, 0, 0, 0],
78+
[0, 0, 0, 0],
79+
[0, 0, 0, 0],
80+
[0, 0, 0, 0] ]
81+
82+
if solveNQUtil(board, 0) == False:
83+
print ("Solution does not exist")
84+
return False
85+
86+
printSolution(board)
87+
return True
88+
89+
# Driver Code
90+
solveNQ()
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,193 @@
1+
// C++ program to solve Traveling Salesman Problem
2+
// using Branch and Bound.
3+
#include <bits/stdc++.h>
4+
using namespace std;
5+
const int N = 4;
6+
7+
// final_path[] stores the final solution ie, the
8+
// path of the salesman.
9+
int final_path[N+1];
10+
11+
// visited[] keeps track of the already visited nodes
12+
// in a particular path
13+
bool visited[N];
14+
15+
// Stores the final minimum weight of shortest tour.
16+
int final_res = INT_MAX;
17+
18+
// Function to copy temporary solution to
19+
// the final solution
20+
void copyToFinal(int curr_path[])
21+
{
22+
for (int i=0; i<N; i++)
23+
final_path[i] = curr_path[i];
24+
final_path[N] = curr_path[0];
25+
}
26+
27+
// Function to find the minimum edge cost
28+
// having an end at the vertex i
29+
int firstMin(int adj[N][N], int i)
30+
{
31+
int min = INT_MAX;
32+
for (int k=0; k<N; k++)
33+
if (adj[i][k]<min && i != k)
34+
min = adj[i][k];
35+
return min;
36+
}
37+
38+
// function to find the second minimum edge cost
39+
// having an end at the vertex i
40+
int secondMin(int adj[N][N], int i)
41+
{
42+
int first = INT_MAX, second = INT_MAX;
43+
for (int j=0; j<N; j++)
44+
{
45+
if (i == j)
46+
continue;
47+
48+
if (adj[i][j] <= first)
49+
{
50+
second = first;
51+
first = adj[i][j];
52+
}
53+
else if (adj[i][j] <= second &&
54+
adj[i][j] != first)
55+
second = adj[i][j];
56+
}
57+
return second;
58+
}
59+
60+
// function that takes as arguments:
61+
// curr_bound -> lower bound of the root node
62+
// curr_weight-> stores the weight of the path so far
63+
// level-> current level while moving in the search
64+
// space tree
65+
// curr_path[] -> where the solution is being stored which
66+
// would later be copied to final_path[]
67+
void TSPRec(int adj[N][N], int curr_bound, int curr_weight,
68+
int level, int curr_path[])
69+
{
70+
// base case is when we have reached level N which
71+
// means we have covered all the nodes once
72+
if (level==N)
73+
{
74+
// check if there is an edge from last vertex in
75+
// path back to the first vertex
76+
if (adj[curr_path[level-1]][curr_path[0]] != 0)
77+
{
78+
// curr_res has the total weight of the
79+
// solution we got
80+
int curr_res = curr_weight +
81+
adj[curr_path[level-1]][curr_path[0]];
82+
83+
// Update final result and final path if
84+
// current result is better.
85+
if (curr_res < final_res)
86+
{
87+
copyToFinal(curr_path);
88+
final_res = curr_res;
89+
}
90+
}
91+
return;
92+
}
93+
94+
// for any other level iterate for all vertices to
95+
// build the search space tree recursively
96+
for (int i=0; i<N; i++)
97+
{
98+
// Consider next vertex if it is not same (diagonal
99+
// entry in adjacency matrix and not visited
100+
// already)
101+
if (adj[curr_path[level-1]][i] != 0 &&
102+
visited[i] == false)
103+
{
104+
int temp = curr_bound;
105+
curr_weight += adj[curr_path[level-1]][i];
106+
107+
// different computation of curr_bound for
108+
// level 2 from the other levels
109+
if (level==1)
110+
curr_bound -= ((firstMin(adj, curr_path[level-1]) +
111+
firstMin(adj, i))/2);
112+
else
113+
curr_bound -= ((secondMin(adj, curr_path[level-1]) +
114+
firstMin(adj, i))/2);
115+
116+
// curr_bound + curr_weight is the actual lower bound
117+
// for the node that we have arrived on
118+
// If current lower bound < final_res, we need to explore
119+
// the node further
120+
if (curr_bound + curr_weight < final_res)
121+
{
122+
curr_path[level] = i;
123+
visited[i] = true;
124+
125+
// call TSPRec for the next level
126+
TSPRec(adj, curr_bound, curr_weight, level+1,
127+
curr_path);
128+
}
129+
130+
// Else we have to prune the node by resetting
131+
// all changes to curr_weight and curr_bound
132+
curr_weight -= adj[curr_path[level-1]][i];
133+
curr_bound = temp;
134+
135+
// Also reset the visited array
136+
memset(visited, false, sizeof(visited));
137+
for (int j=0; j<=level-1; j++)
138+
visited[curr_path[j]] = true;
139+
}
140+
}
141+
}
142+
143+
// This function sets up final_path[]
144+
void TSP(int adj[N][N])
145+
{
146+
int curr_path[N+1];
147+
148+
// Calculate initial lower bound for the root node
149+
// using the formula 1/2 * (sum of first min +
150+
// second min) for all edges.
151+
// Also initialize the curr_path and visited array
152+
int curr_bound = 0;
153+
memset(curr_path, -1, sizeof(curr_path));
154+
memset(visited, 0, sizeof(curr_path));
155+
156+
// Compute initial bound
157+
for (int i=0; i<N; i++)
158+
curr_bound += (firstMin(adj, i) +
159+
secondMin(adj, i));
160+
161+
// Rounding off the lower bound to an integer
162+
curr_bound = (curr_bound&1)? curr_bound/2 + 1 :
163+
curr_bound/2;
164+
165+
// We start at vertex 1 so the first vertex
166+
// in curr_path[] is 0
167+
visited[0] = true;
168+
curr_path[0] = 0;
169+
170+
// Call to TSPRec for curr_weight equal to
171+
// 0 and level 1
172+
TSPRec(adj, curr_bound, 0, 1, curr_path);
173+
}
174+
175+
// Driver code
176+
int main()
177+
{
178+
//Adjacency matrix for the given graph
179+
int adj[N][N] = { {0, 10, 15, 20},
180+
{10, 0, 35, 25},
181+
{15, 35, 0, 30},
182+
{20, 25, 30, 0}
183+
};
184+
185+
TSP(adj);
186+
187+
printf("Minimum cost : %d\n", final_res);
188+
printf("Path Taken : ");
189+
for (int i=0; i<=N; i++)
190+
printf("%d ", final_path[i]);
191+
192+
return 0;
193+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
# A Simple Merge based O(n) Python 3 solution
2+
# to find median of two sorted lists
3+
4+
# This function returns median of ar1[] and ar2[].
5+
# Assumptions in this function:
6+
# Both ar1[] and ar2[] are sorted arrays
7+
# Both have n elements
8+
def getMedian( ar1, ar2 , n):
9+
i = 0 # Current index of i/p list ar1[]
10+
11+
j = 0 # Current index of i/p list ar2[]
12+
13+
m1 = -1
14+
m2 = -1
15+
16+
# Since there are 2n elements, median
17+
# will be average of elements at index
18+
# n-1 and n in the array obtained after
19+
# merging ar1 and ar2
20+
count = 0
21+
while count < n + 1:
22+
count += 1
23+
24+
# Below is to handle case where all
25+
# elements of ar1[] are smaller than
26+
# smallest(or first) element of ar2[]
27+
if i == n:
28+
m1 = m2
29+
m2 = ar2[0]
30+
break
31+
32+
# Below is to handle case where all
33+
# elements of ar2[] are smaller than
34+
# smallest(or first) element of ar1[]
35+
elif j == n:
36+
m1 = m2
37+
m2 = ar1[0]
38+
break
39+
if ar1[i] < ar2[j]:
40+
m1 = m2 # Store the prev median
41+
m2 = ar1[i]
42+
i += 1
43+
else:
44+
m1 = m2 # Store the prev median
45+
m2 = ar2[j]
46+
j += 1
47+
return (m1 + m2)/2
48+
49+
# Driver code to test above function
50+
ar1 = [1, 12, 15, 26, 38]
51+
ar2 = [2, 13, 17, 30, 45]
52+
n1 = len(ar1)
53+
n2 = len(ar2)
54+
if n1 == n2:
55+
print("Median is ", getMedian(ar1, ar2, n1))
56+
else:
57+
print("Doesn't work for arrays of unequal size")
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
#A naive recursive implementation of 0-1 Knapsack Problem
2+
3+
# Returns the maximum value that can be put in a knapsack of
4+
# capacity W
5+
def knapSack(W , wt , val , n):
6+
7+
# Base Case
8+
if n == 0 or W == 0 :
9+
return 0
10+
11+
# If weight of the nth item is more than Knapsack of capacity
12+
# W, then this item cannot be included in the optimal solution
13+
if (wt[n-1] > W):
14+
return knapSack(W , wt , val , n-1)
15+
16+
# return the maximum of two cases:
17+
# (1) nth item included
18+
# (2) not included
19+
else:
20+
return max(val[n-1] + knapSack(W-wt[n-1] , wt , val , n-1),
21+
knapSack(W , wt , val , n-1))
22+
23+
# end of function knapSack
24+
25+
# To test above function
26+
val = [60, 100, 120]
27+
wt = [10, 20, 30]
28+
W = 50
29+
n = len(val)
30+
print(knapSack(W , wt , val , n))

0 commit comments

Comments
 (0)