0% found this document useful (0 votes)
14 views10 pages

Import Daa Codes

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views10 pages

Import Daa Codes

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 10

1.

prims ------------------------------------
import sys
class Graph:
def __init__(self, vertices):
self.V = vertices
self.graph = [[0 for _ in range(vertices)] for _ in range(vertices)]
def min_key(self, key, mst_set):
min_val = sys.maxsize
min_index = -1
for v in range(self.V):
if key[v] < min_val and not mst_set[v]:
min_val = key[v]
min_index = v
return min_index
def prim_mst(self):
parent = [-1] * self.V
key = [sys.maxsize] * self.V
key[0] = 0
mst_set = [False] * self.V
for _ in range(self.V):
u = self.min_key(key, mst_set)
mst_set[u] = True
for v in range(self.V):
if self.graph[u][v] > 0 and not mst_set[v] and key[v] >
self.graph[u][v]:
key[v] = self.graph[u][v]
parent[v] = u
self.print_mst(parent)
def print_mst(self, parent):
print("Edge \tWeight")
for i in range(1, self.V):
print(parent[i], "-", i, "\t", self.graph[i][parent[i]])
def create_graph():
vertices = int(input("Enter the number of vertices: "))
g = Graph(vertices)
print("Enter the adjacency matrix (enter 0 for no edge):")
for i in range(vertices):
for j in range(vertices):
g.graph[i][j] = int(input(f"Enter weight between {i} and {j}: "))
return g
def main():
g = create_graph()
g.prim_mst()
if __name__ == "__main__":
main()

2.kruskals
-----------------------------------------------------------------------------------
---------------

class Graph:
def __init__(self, vertices):
self.V = vertices
self.graph = []

def add_edge(self, u, v, w):


self.graph.append([u, v, w])

def find_parent(self, parent, i):


if parent[i] == i:
return i
return self.find_parent(parent, parent[i])

def union(self, parent, rank, x, y):


x_root = self.find_parent(parent, x)
y_root = self.find_parent(parent, y)

if rank[x_root] < rank[y_root]:


parent[x_root] = y_root
elif rank[x_root] > rank[y_root]:
parent[y_root] = x_root
else:
parent[y_root] = x_root
rank[x_root] += 1

def kruskal_mst(self):
result = []
i, e = 0, 0
self.graph = sorted(self.graph, key=lambda item: item[2])
parent = []
rank = []

for node in range(self.V):


parent.append(node)
rank.append(0)

while e < self.V - 1:


u, v, w = self.graph[i]
i += 1
x = self.find_parent(parent, u)
y = self.find_parent(parent, v)

if x != y:
e += 1
result.append([u, v, w])
self.union(parent, rank, x, y)

print("Edge \tWeight")
for u, v, weight in result:
print(f"{u} - {v}\t{weight}")

g = Graph(4)
g.add_edge(0, 1, 10)
g.add_edge(0, 2, 6)
g.add_edge(0, 3, 5)
g.add_edge(1, 3, 15)
g.add_edge(2, 3, 4)

g.kruskal_mst()

3.mergesort
----------------------------------------------------------------------------------

def merge_sort(arr):
if len(arr) > 1:
mid = len(arr) // 2
left_half = arr[:mid]
right_half = arr[mid:]
merge_sort(left_half)
merge_sort(right_half)
i = j = k = 0
while i < len(left_half) and j < len(right_half):
if left_half[i] < right_half[j]:
arr[k] = left_half[i]
i += 1
else:
arr[k] = right_half[j]
j += 1
k += 1
while i < len(left_half):
arr[k] = left_half[i]
i += 1
k += 1
while j < len(right_half):
arr[k] = right_half[j]
j += 1
k += 1
def print_array(arr):
for element in arr:
print(element, end=" ")
print()
def get_input():
n = int(input("Enter the number of elements: "))
arr = []
print("Enter the elements:")
for _ in range(n):
arr.append(int(input()))
return arr
def main():
arr = get_input()
print("Original array:", end=" ")
print_array(arr)
merge_sort(arr)
print("Sorted array:", end=" ")
print_array(arr)
if __name__ == "__main__":
main()

#Enter the number of elements: 6


# Enter the elements:
# 12
# 11
# 13
# 5
# 6
# 7

4.quicksort
-----------------------------------------------------------------------------------
--------------

def partition(arr, low, high):


pivot = arr[high]
i = low - 1
for j in range(low, high):
if arr[j] <= pivot:
i += 1
arr[i], arr[j] = arr[j], arr[i]
arr[i + 1], arr[high] = arr[high], arr[i + 1]
return i + 1
def quick_sort(arr, low, high):
if low < high:
pi = partition(arr, low, high)
quick_sort(arr, low, pi - 1)
quick_sort(arr, pi + 1, high)
def print_array(arr):
for element in arr:
print(element, end=" ")
print()
def get_input():
n = int(input("Enter the number of elements: "))
arr = []
print("Enter the elements:")
for _ in range(n):
arr.append(int(input()))
return arr
def main():
arr = get_input()
print("Original array:", end=" ")
print_array(arr)
quick_sort(arr, 0, len(arr) - 1)
print("Sorted array:", end=" ")
print_array(arr)
if __name__ == "__main__":
main()
# Enter the number of elements: 4
# Enter the elements:
# 5
# 3
# 6
# 1

5. matrix cm -------------------------------------------------------
def matrix_chain_multiplication(p):
n = len(p)
dp = [[0] * n for _ in range(n)]
for chain_length in range(2, n):
for i in range(1, n - chain_length + 1):
j = i + chain_length - 1
dp[i][j] = float('inf')
for k in range(i, j):
cost = dp[i][k] + dp[k+1][j] + p[i-1] * p[k] * p[j]
if cost < dp[i][j]:
dp[i][j] = cost
return dp[1][n-1]
def get_matrix_dimensions():
n = int(input("Enter the number of matrices: "))
dimensions = []
print("Enter the dimensions of each matrix (row col):")
for i in range(n):
dim = tuple(map(int, input().split()))
dimensions.append(dim)
return dimensions
if __name__ == "__main__":
dimensions = get_matrix_dimensions()
p = [dimensions[i][0] for i in range(len(dimensions))] + [dimensions[-1][1]]
print("Minimum number of multiplications is:", matrix_chain_multiplication(p))

# Enter the number of matrices: 5


# Enter the dimensions of each matrix (row col):
# 12 3
# 1 5
# 23
# 24 5
# 6 5
# Minimum number of multiplications is: 786

6.strongly
connected----------------------------------------------------------------------

from collections import defaultdict


class Graph:
def __init__(self, vertices):
self.V = vertices
self.graph = defaultdict(list)
self.time = 0
def add_edge(self, u, v):
self.graph[u].append(v)
def SCC_util(self, u, low, disc, stack_member, st):
disc[u] = self.time
low[u] = self.time
self.time += 1
stack_member[u] = True
st.append(u)
for v in self.graph[u]:
if disc[v] == -1:
self.SCC_util(v, low, disc, stack_member, st)
low[u] = min(low[u], low[v])
elif stack_member[v]:
low[u] = min(low[u], disc[v])
w = -1
if low[u] == disc[u]:
while w != u:
w = st.pop()
print(w, end=" ")
stack_member[w] = False
print("")
def SCC(self):
disc = [-1] * self.V
low = [-1] * self.V
stack_member = [False] * self.V
st = []
for i in range(self.V):
if disc[i] == -1:
self.SCC_util(i, low, disc, stack_member, st)
g = Graph(5)
g.add_edge(0, 1)
g.add_edge(1, 2)
g.add_edge(2, 0)
g.add_edge(1, 3)
g.add_edge(3, 4)
print("Strongly Connected Components:")
g.SCC()
# Strongly Connected Components:
# 4
# 3
# 2 1 0

7. shortest
path--------------------------------------------------------------------------
E = float('inf')
def floyd_warshall(graph):
V = len(graph)
dist = [[0] * V for _ in range(V)]
for i in range(V):
for j in range(V):
if graph[i][j] != E:
dist[i][j] = graph[i][j]
else:
dist[i][j] = E
for k in range(V):
for i in range(V):
for j in range(V):
if dist[i][k] != E and dist[k][j] != E:
dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j])

return dist
graph = [
[0, 5, E, 10],
[E, 0, 3, E],
[E, E, 0, 1],
[E, E, E, 0]
]

distances = floyd_warshall(graph)
for row in distances:
print(row)

8. knapsack -
0/1--------------------------------------------------------------------------------
---------

def fractional_knapsack(values, weights, capacity):


n = len(values)
value_per_weight = [(values[i] / weights[i], weights[i], values[i]) for i in
range(n)]
value_per_weight.sort(reverse=True)
total_value = 0
knapsack = [0] * n
for i in range(n):
if capacity == 0:
break
weight = min(value_per_weight[i][1], capacity)
total_value += weight * value_per_weight[i][0]
knapsack[value_per_weight.index((value_per_weight[i][0],
value_per_weight[i][1], value_per_weight[i][2]))] = weight
capacity -= weight
return total_value, knapsack
def main():
print("Enter the number of items:")
n = int(input())
values = []
weights = []
print("Enter the values and weights of each item:")
for _ in range(n):
v, w = map(int, input().split())
values.append(v)
weights.append(w)
print("Enter the capacity of the knapsack:")
capacity = int(input())
total_value, knapsack = fractional_knapsack(values, weights, capacity)
print("Total value obtained:", total_value)
print("Items in knapsack (fractional):", knapsack)
if __name__ == "__main__":
main()

# Enter the number of items:


# 3
# Enter the values and weights of each item:
# 120 5
# 100 6
# 30 3
# Enter the capacity of the knapsack:
# 12

9. OBST
-----------------------------------------------------------------------------------
--------------------

def optimal_bst(keys, frequencies):


n = len(keys)
dp = [[0] * n for _ in range(n)]
for i in range(n):
dp[i][i] = frequencies[i]
for cl in range(2, n + 1):
for i in range(n - cl + 1):
j = i + cl - 1
dp[i][j] = float('inf')
freq_sum = sum(frequencies[i:j + 1])
for r in range(i, j + 1):
c = dp[i][r - 1] if r > i else 0
c += dp[r + 1][j] if r < j else 0
dp[i][j] = min(dp[i][j], c + freq_sum)

return dp[0][n - 1]
# Example usage:
keys = [10, 20, 390]
frequencies = [34, 8, 50]
result = optimal_bst(keys, frequencies)
print("Minimum cost of optimal BST:", result)

10. travelling salesman problem


-----------------------------------------------------------------------------------
-

def tsp(graph):
n = len(graph)
memo = [[float('inf')] * n for _ in range(1 << n)]
memo[1][0] = 0
parent = [[-1] * n for _ in range(1 << n)]
for subset in range(1, 1 << n):
for u in range(n):
if subset & (1 << u):
for v in range(n):
if subset & (1 << v) and u != v:
if memo[subset][v] > memo[subset ^ (1 << v)][u] + graph[u]
[v]:
memo[subset][v] = memo[subset ^ (1 << v)][u] + graph[u]
[v]
parent[subset][v] = u
min_cost = min(memo[-1][v] + graph[v][0] for v in range(1, n))
path = [0]
subset = (1 << n) - 1
v = min(range(n), key=lambda x: memo[subset][x] + graph[x][0])
while v != -1:
u = parent[subset][v]
subset ^= (1 << v)
path.append(v)
v = u
return min_cost, path[::-1]
graph = [
[0, 10, 15, 20],
[10, 0, 35, 25],
[15, 35, 0, 30],
[20, 25, 30, 0]
]
min_cost, path = tsp(graph)
print("Minimum cost to visit all cities:", min_cost)
print("Optimal path:", path)

11.hamiltonian
-----------------------------------------------------------------------------------
---------------------

def is_valid(graph, path, pos, v):


if graph[path[pos - 1]][v] == 0:
return False
if v in path:
return False
return True
def hamiltonian_util(graph, path, pos):
if pos == len(graph):
if graph[path[pos - 1]][path[0]] == 1:
return True
else:
return False
for v in range(1, len(graph)):
if is_valid(graph, path, pos, v):
path[pos] = v
if hamiltonian_util(graph, path, pos + 1):
return True
path[pos] = -1
return False
def hamiltonian_circuit(graph):
n = len(graph)
path = [-1] * n
path[0] = 0
if not hamiltonian_util(graph, path, 1):
print("No Hamiltonian Circuit exists")
return False
print("Hamiltonian Circuit exists: ", end="")
for vertex in path:
print(vertex, end=" ")
print(path[0])
return True
graph = [
[0, 1, 1, 1, 0],
[1, 0, 1, 0, 1],
[1, 1, 0, 1, 1],
[1, 0, 1, 0, 1],
[0, 1, 1, 1, 0]
]
hamiltonian_circuit(graph)

12 warshall algo
----------------------------------------------------------------------------

def warshall_algorithm(graph):
num_vertices = len(graph)
transitive_closure = [[0] * num_vertices for _ in range(num_vertices)]
for i in range(num_vertices):
for j in range(num_vertices):
transitive_closure[i][j] = graph[i][j]
for k in range(num_vertices):
for i in range(num_vertices):
for j in range(num_vertices):
transitive_closure[i][j] = transitive_closure[i][j] or
(transitive_closure[i][k] and transitive_closure[k][j])
return transitive_closure
graph = [
[0, 1, 0, 0],
[0, 0, 1, 0],
[0, 0, 0, 1],
[1, 0, 0, 0]]
transitive_closure = warshall_algorithm(graph)
print("Transitive Closure:")
for row in transitive_closure:
print(row)

12. Floyd warshall


-----------------------------------------------------------------------------------
------------------

E = float('inf')

def floyd_warshall(graph):
V = len(graph)
dist = [[0] * V for _ in range(V)]
for i in range(V):
for j in range(V):
if graph[i][j] != E:
dist[i][j] = graph[i][j]
else:
dist[i][j] = E
for k in range(V):
for i in range(V):
for j in range(V):
if dist[i][k] != E and dist[k][j] != E:
dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j])
return dist

graph = [[0, 5, float('inf'), 10],


[float('inf'), 0, 3, float('inf')],
[float('inf'), float('inf'), 0, 1],
[float('inf'), float('inf'), float('inf'), 0]]

distances = floyd_warshall(graph)
for row in distances:
print(row)

You might also like