├── Minimal Coin Change (Greedy Method).py ├── Run Length Encoding.py ├── Hamming Distance.py ├── Counting Sort.py ├── Edit Distance Recursive.py ├── Fractional Knapsack.py ├── MiniMax Algorithm.py ├── Interpolation Search.py ├── Bucket Sort.py ├── README.md ├── LICENSE ├── Edit Distance.py ├── 0-1 Knapsack.py ├── Key Index Search and Sort.py ├── Kruskal's Algorithm.py ├── LCS.py ├── BFS and DFS.py ├── Dijkstra's Algorithm.py └── Undirected Graph Representations.py /Minimal Coin Change (Greedy Method).py: -------------------------------------------------------------------------------- 1 | C=[1000, 500, 100, 50, 20, 10, 5, 2, 1] 2 | remaining=93 3 | count=0 4 | coins=[] 5 | for i in C: 6 | count = count + (remaining//i) 7 | coins+=[i]*(remaining//i) 8 | remaining = remaining - ((remaining//i)*i) 9 | print('Minimal Number of Coins:',count) 10 | print('Minimal Change:',coins) 11 | 12 | ## OUTPUT: 13 | 14 | ''' 15 | Minimal Number of Coins: 5 16 | Minimal Change: [50, 20, 20, 2, 1] 17 | 18 | ''' 19 | -------------------------------------------------------------------------------- /Run Length Encoding.py: -------------------------------------------------------------------------------- 1 | def RLE(string): 2 | 3 | encoded='' 4 | i = 0 5 | 6 | while i < len(string)- 1: 7 | count = 1 8 | 9 | while (i < len(string) - 1 and string[i] == string[i + 1]): 10 | count += 1 11 | i += 1 12 | i += 1 13 | 14 | encoded+= string[i - 1] +str(count) 15 | 16 | return encoded 17 | 18 | string = "ww22222wwwwwaaaadexpppxxxxxywww" 19 | x=RLE(string) 20 | print('Encoded String:',x) 21 | 22 | ##OUTPUT: 23 | ''' 24 | 25 | Encoded String: w4a3d1e1x6y1w3 26 | ''' -------------------------------------------------------------------------------- /Hamming Distance.py: -------------------------------------------------------------------------------- 1 | 2 | def hamming_dist(str1, str2): 3 | 4 | count = 0 5 | char1='' 6 | char2='' 7 | 8 | 9 | if len(str1)>len(str2): 10 | x=len(str2) 11 | else: 12 | x=len(str1) 13 | i=0 14 | 15 | while(i < x): 16 | if(str1[i] != str2[i]): 17 | count += 1 18 | char1=char1+str1[i] 19 | char2=char2+str2[i] 20 | i += 1 21 | 22 | return count,char1,char2 23 | 24 | 25 | str1 = "Moscow" 26 | str2 = "Morocco" 27 | 28 | print(hamming_dist(str1, str2)) 29 | -------------------------------------------------------------------------------- /Counting Sort.py: -------------------------------------------------------------------------------- 1 | def countingSort(array): 2 | size = len(array) 3 | output = [0] * size 4 | count = [0] * 10 5 | 6 | for i in range(0, size): 7 | count[array[i]] += 1 8 | 9 | for j in range(1,10): 10 | count[j] += count[j-1] 11 | 12 | a = size-1 13 | while a >= 0: 14 | output[count[array[a]]-1] = array[a] 15 | count[array[a]] -= 1 16 | a -= 1 17 | 18 | return output 19 | 20 | unsorted_array = [4,2,2,2,8,8,3,3,1,7] 21 | sorted_array=countingSort(unsorted_array) 22 | print('Sorted Array:',sorted_array) 23 | 24 | ## OUTPUT: 25 | ''' 26 | Sorted Array: [1, 2, 2, 2, 3, 3, 4, 7, 8, 8] 27 | 28 | ''' -------------------------------------------------------------------------------- /Edit Distance Recursive.py: -------------------------------------------------------------------------------- 1 | def editDistance(str1, str2, m, n,ci=1,crm=1,crp=1): 2 | 3 | if m == 0: 4 | return n 5 | if n == 0: 6 | return m 7 | 8 | if str1[m-1] == str2[n-1]: 9 | return editDistance(str1, str2, m-1, n-1,ci,crm,crp) 10 | 11 | return min( editDistance(str1, str2, m, n-1,ci,crm,crp)+ci, # Insert 12 | editDistance(str1, str2, m-1, n,ci,crm,crp)+crm, # Remove 13 | editDistance(str1, str2, m-1, n-1,ci,crm,crp)+crp ) # Replace 14 | 15 | 16 | 17 | str1 = "tea" 18 | str2 = "set" 19 | ed=editDistance(str1, str2, len(str1), len(str2)) 20 | print ('Minimum Edit Distance:',ed) 21 | 22 | ## OUTPUT: 23 | ''' 24 | Minimum Edit Distance: 2 25 | ''' -------------------------------------------------------------------------------- /Fractional Knapsack.py: -------------------------------------------------------------------------------- 1 | def fractionalKnapsack(weights,values,capacity): 2 | 3 | ratio = [v/w for v, w in zip(values, weights)] 4 | value_index_array=sorted(zip(ratio, weights),reverse=True) 5 | total = 0 6 | 7 | for i in value_index_array: 8 | if i[1]<=capacity: 9 | capacity-=i[1] 10 | total+=i[0]*i[1] 11 | else: 12 | total+=i[0]*(capacity) 13 | break 14 | 15 | return total 16 | 17 | 18 | item_weights = [10, 40, 20, 30] 19 | item_values = [60, 40, 100, 120] 20 | max_capacity = 50 21 | 22 | total = fractionalKnapsack(item_weights,item_values,max_capacity) 23 | 24 | print('Maximum value we can obtain:',total) 25 | 26 | ##OUTPUT: 27 | ''' 28 | Maximum value we can obtain: 240.0 29 | 30 | ''' 31 | -------------------------------------------------------------------------------- /MiniMax Algorithm.py: -------------------------------------------------------------------------------- 1 | import math 2 | 3 | def minimax (current, node_index,turn, scores,targetDepth): 4 | 5 | if (current == targetDepth): 6 | return scores[node_index] 7 | 8 | if (turn): 9 | 10 | return max(minimax(current + 1, node_index * 2,False, scores, targetDepth), 11 | minimax(current + 1, node_index * 2 + 1,False, scores, targetDepth)) 12 | 13 | else: 14 | return min(minimax(current + 1, node_index * 2,True, scores, targetDepth), 15 | minimax(current + 1, node_index * 2 + 1,True, scores, targetDepth)) 16 | 17 | scores = [-1,3,5,1,-6,-4,0,9] 18 | 19 | treeDepth = math.log(len(scores), 2) 20 | 21 | 22 | 23 | result = minimax(0, 0, True, scores, treeDepth) 24 | 25 | print("The optimal value is:",result, end = "") 26 | 27 | ''' 28 | The optimal value is: 3 29 | 30 | ''' -------------------------------------------------------------------------------- /Interpolation Search.py: -------------------------------------------------------------------------------- 1 | def interpolationSearch(array, x): 2 | 3 | (left, right) = (0, len(array) - 1) 4 | 5 | while array[right] != array[left] and array[left] <= x <= array[right]: 6 | 7 | mid = left + (x - array[left]) * (right - left) // (array[right] - array[left]) 8 | 9 | if x == array[mid]: 10 | return mid 11 | 12 | elif x < array[mid]: 13 | right = mid - 1 14 | 15 | 16 | else: 17 | left = mid + 1 18 | 19 | if x == array[left]: 20 | return left 21 | 22 | return -1 23 | 24 | 25 | 26 | array = [2, 5, 6, 8, 9, 10] 27 | key = 6 28 | 29 | index = interpolationSearch(array, key) 30 | 31 | if index != -1: 32 | print("Element found at index", index) 33 | else: 34 | print("Element found not in the list") 35 | 36 | ##OUTPUT: 37 | ''' 38 | Element found at index 2 39 | ''' 40 | -------------------------------------------------------------------------------- /Bucket Sort.py: -------------------------------------------------------------------------------- 1 | def insertionSort(b): 2 | for i in range(1, len(b)): 3 | up = b[i] 4 | j = i - 1 5 | while j >= 0 and b[j] > up: 6 | b[j + 1] = b[j] 7 | j -= 1 8 | b[j + 1] = up 9 | return b 10 | 11 | def bucketSort(A): 12 | n=len(A) 13 | arr = [] 14 | for i in range(n): 15 | arr.append([]) 16 | for i in range(0,n): 17 | arr[int(n*A[i])].append(A[i]) 18 | 19 | for i in range(0,n): 20 | arr[i] = insertionSort(arr[i]) 21 | 22 | 23 | k = 0 24 | for i in range(n): 25 | for j in range(len(arr[i])): 26 | A[k] = arr[i][j] 27 | k += 1 28 | return A 29 | 30 | 31 | x= [0.77,0.16,0.39,0.26,0.71,0.95,0.21,0.12,0.23,0.68] 32 | 33 | print("Sorted Array is:",bucketSort(x)) 34 | 35 | 36 | ## OUTPUT: 37 | 38 | ''' 39 | Sorted Array is: [0.12, 0.16, 0.21, 0.23, 0.26, 0.39, 0.68, 0.71, 0.77, 0.95] 40 | 41 | ''' 42 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Algorithms-CSE221 2 | 3 | ## Programming Language Used: 4 | - Python 3 5 | 6 | ## Content: (Updating...) 7 | - Merge Sort 8 | - Quick Sort 9 | - Counting Sort 10 | - Bucket Sort 11 | - Radix Sort 12 | - Key Index Search and Sort 13 | - Binary Search 14 | - Ternary Search 15 | - Jump Search 16 | - Interpolation Search (improved variant of binary search) 17 | - Graph Representations (Undirected) 18 | - BFS and DFS Algorithms 19 | - Topological Sort 20 | - Minimum Coin Change (Greedy Method) 21 | - Dijkstra's Algorithm 22 | - Kruskal's Algorithm 23 | - Prim's Algorithm 24 | - LCS Algorithm 25 | - Fractional Knapsack (aka Continuous Knapsack) 26 | - 0-1 Knapsack Problem 27 | - Hamming Distance 28 | - Edit Distance Recursive Algorithm (Levensthein Distance if all of the operations are of cost = 1) 29 | - Edit Distance Dynamic Programming Algorithm 30 | - Run Length Encoding 31 | - Huffman Coding 32 | - Strassen’s Matrix Multiplication 33 | - Matrix Chain Multiplication (Dynamic Programming) 34 | - MiniMax Algorithm 35 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2021 Farhadul Islam 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /Edit Distance.py: -------------------------------------------------------------------------------- 1 | def editDistance(str1, str2, m, n, ci=1,crm=1,crp=1): 2 | 3 | 4 | dp = [[0 for i in range(n + 1)] for j in range(m + 1)] 5 | 6 | for i in range(m + 1): 7 | for j in range(n + 1): 8 | 9 | 10 | if i == 0: 11 | dp[i][j] = j 12 | 13 | elif j == 0: 14 | dp[i][j] = i 15 | 16 | elif str1[i-1] == str2[j-1]: 17 | dp[i][j] = dp[i-1][j-1] 18 | 19 | else: 20 | dp[i][j] = min((dp[i][j-1] + ci), # Insert 21 | (dp[i-1][j] + crm), # Remove 22 | (dp[i-1][j-1] + crp)) # Replace 23 | 24 | 25 | return dp[m][n] ##or dp[-1][-1] 26 | 27 | 28 | str1 = "MARCH" 29 | str2 = "CART" 30 | cost_insert = 1 31 | cost_remove = 1 32 | cost_replace = 1 33 | ed=editDistance(str1, str2, len(str1), len(str2), cost_insert,cost_remove,cost_replace) 34 | print('Minimum Edit Distance:',ed) 35 | 36 | ## OUTPUT: 37 | ''' 38 | Minimum Edit Distance: 3 39 | 40 | ''' -------------------------------------------------------------------------------- /0-1 Knapsack.py: -------------------------------------------------------------------------------- 1 | def knapsack(n, c, w, v): 2 | 3 | K = [[0 for j in range(c + 1)] for i in range(n + 1)] 4 | for i in range(n + 1): 5 | for j in range(c + 1): 6 | if i == 0 or j == 0: 7 | K[i][j] = 0 8 | elif w[i-1] <= j: 9 | K[i][j] = max(v[i-1] + K[i-1][j-w[i-1]], K[i-1][j]) 10 | else: 11 | K[i][j] = K[i-1][j] 12 | 13 | 14 | return K 15 | 16 | def show(n, c, w, value, items): 17 | 18 | j = c 19 | selected=[] 20 | for i in range(n,0,-1): 21 | if value[i][j] > value[i-1][j]: 22 | selected.insert(0,items[i-1]) 23 | j -= w[i - 1] 24 | 25 | print('Items Taken:') 26 | print(*selected,sep=', ') 27 | print('Total amount taken:', value[n][c]) 28 | 29 | 30 | values=[60, 100, 120 ] 31 | weights=[10, 20, 30] 32 | item_names=['Spice','Sugar','Rice'] 33 | 34 | 35 | max_weight=50 36 | no_of_items=3 37 | 38 | 39 | k=knapsack(no_of_items,max_weight,weights,values) 40 | show(no_of_items,max_weight,weights,k,item_names) 41 | 42 | ##OUTPUT: 43 | ''' 44 | Items Taken: 45 | Sugar, Rice 46 | Total amount taken: 220 47 | 48 | ''' -------------------------------------------------------------------------------- /Key Index Search and Sort.py: -------------------------------------------------------------------------------- 1 | class KeyIndex: 2 | def __init__(self,a): 3 | self.a=a 4 | self.aux=[0]*(max(a)+1) 5 | for i in self.a: 6 | self.aux[i]+=1 7 | 8 | def search(self,item): 9 | if self.aux[item]!=0: 10 | return True 11 | else: 12 | return False 13 | 14 | def sort(self): 15 | sorted_a=[] 16 | for i in range(len(self.aux)): 17 | if self.aux[i]!=0: 18 | sorted_a+=[i]*self.aux[i] 19 | return sorted_a 20 | def sort_neg(self,a): 21 | neg_min=min(a) 22 | x=neg_min*-1 23 | for i in range(len(a)): 24 | a[i]+=x 25 | aux2=[0]*(max(a)+1) 26 | for i in a: 27 | aux2[i]+=1 28 | 29 | sorted_neg_a=[] 30 | for i in range(len(aux2)): 31 | if aux2[i]!=0: 32 | sorted_neg_a+=[i]*aux2[i] 33 | 34 | for i in range(len(sorted_neg_a)): 35 | sorted_neg_a[i]+=neg_min 36 | 37 | return sorted_neg_a 38 | 39 | key_ind=KeyIndex([4,2,3,4,7,4]) 40 | print('Is 3 in the array:',key_ind.search(3)) 41 | print('Sorted Array:',key_ind.sort()) 42 | print('Sorted Array with Negative Numbers:',key_ind.sort_neg([4,-2,3,-4,7,4])) 43 | ##OUPUT: 44 | ''' 45 | Is 3 in the array: True 46 | Sorted Array: [2, 3, 4, 4, 4, 7] 47 | Sorted Array with Negative Numbers: [-4, -2, 3, 4, 4, 7] 48 | 49 | ''' 50 | -------------------------------------------------------------------------------- /Kruskal's Algorithm.py: -------------------------------------------------------------------------------- 1 | 2 | parent = {} 3 | 4 | def makeSet(i): 5 | 6 | parent[i] = i 7 | 8 | def Find(k): 9 | 10 | if parent[k] == k: 11 | return k 12 | return Find(parent[k]) 13 | 14 | def Union(a, b): 15 | 16 | x = Find(a) 17 | y = Find(b) 18 | 19 | parent[x] = y 20 | 21 | 22 | def kruskalAlgo(edges, N): 23 | 24 | total_min_weight=0 25 | MST = [] 26 | 27 | 28 | for i in range(N): 29 | makeSet(i) 30 | 31 | index = 0 32 | 33 | edges.sort(key=lambda x: x[2]) 34 | 35 | while len(MST) != N - 1: 36 | 37 | (src, dest, weight) = edges[index] 38 | index = index + 1 39 | 40 | 41 | x = Find(src) 42 | y = Find(dest) 43 | 44 | 45 | if x != y: 46 | MST.append((src, dest, weight)) 47 | Union(x, y) 48 | total_min_weight+=weight 49 | 50 | return MST,total_min_weight 51 | 52 | 53 | edges = [ 54 | (0, 1, 7), (1, 2, 8), (0, 3, 5), 55 | (1, 3, 9), (1, 4, 7), (2, 4, 5), 56 | (3, 4, 15), (3, 5, 6), (4, 5, 8), 57 | (4, 6, 9), (5, 6, 11) 58 | ] 59 | 60 | N = 7 61 | 62 | mst,min_w = kruskalAlgo(edges, N) 63 | 64 | print('Edges in the constructed MST:',mst) 65 | print('Minimum Cost Spanning Tree:',min_w) 66 | 67 | 68 | 69 | ##OUTPUT: 70 | ''' 71 | Edges in the constructed MST: [(0, 3, 5), (2, 4, 5), (3, 5, 6), (0, 1, 7), (1, 4, 7), (4, 6, 9)] 72 | Minimum Cost Spanning Tree: 39 73 | ''' 74 | -------------------------------------------------------------------------------- /LCS.py: -------------------------------------------------------------------------------- 1 | class LCS: 2 | def __init__(self,str1,str2): 3 | self.str1=str1 4 | self.str2=str2 5 | self.m=len(str1) 6 | self.n=len(str2) 7 | self.dp = [[0 for x in range(self.n + 1)] for x in range(self.m + 1)] 8 | 9 | def lcs_length(self): 10 | for i in range(self.m): 11 | for j in range(self.n): 12 | if self.str1[i] == self.str2[j]: 13 | self.dp[i+1][j+1]=self.dp[i][j]+1 14 | else: 15 | self.dp[i+1][j+1]=max(self.dp[i][j+1],self.dp[i+1][j]) 16 | 17 | return self.dp[-1][-1] 18 | 19 | def lcs_sequence(self): 20 | index = self.dp[self.m][self.n] 21 | seq = [""] * (index+1) 22 | seq[index] = "" 23 | i,j = self.m,self.n 24 | while i > 0 and j > 0: 25 | if self.str1[i-1] == self.str2[j-1]: 26 | seq[index-1] = self.str1[i-1] 27 | i = i - 1 28 | j = j - 1 29 | index -= 1 30 | elif self.dp[i][j-1] < self.dp[i-1][j]: 31 | i = i - 1 32 | else: 33 | j = j - 1 34 | seq_str=''.join(seq[:-1]) 35 | return seq_str 36 | 37 | 38 | str1 = "CDEFGABC" 39 | str2 = "CEFDABGAC" 40 | MySeq=LCS(str1,str2) 41 | print('Least Common Subsequence length-->',MySeq.lcs_length()) 42 | print('Least Common Subsequence-->',MySeq.lcs_sequence()) 43 | 44 | 45 | ##OUTPUT: 46 | ''' 47 | Least Common Subsequence length--> 6 48 | Least Common Subsequence--> CEFABC 49 | 50 | ''' 51 | -------------------------------------------------------------------------------- /BFS and DFS.py: -------------------------------------------------------------------------------- 1 | class Graph: 2 | def __init__(self, vertices): 3 | self.V = vertices 4 | self.graph = {} 5 | 6 | 7 | def add_edge(self, src, dest): 8 | 9 | ##for adjacency list 10 | 11 | if self.graph.get(src) == None: 12 | self.graph[src]=[dest] 13 | else: 14 | self.graph[src]=self.graph.get(src)+[dest] 15 | 16 | if self.graph.get(dest) == None: 17 | self.graph[dest]=[src] 18 | else: 19 | self.graph[dest]=self.graph.get(dest)+[src] 20 | 21 | def BFS(self, s): 22 | visited = set() 23 | queue = [] 24 | visited.add(s) 25 | queue.append(s) 26 | 27 | while queue: 28 | s = queue.pop(0) 29 | print (s, end = " ") 30 | 31 | for node in self.graph[s]: 32 | if node not in visited: 33 | visited.add(node) 34 | queue.append(node) 35 | 36 | 37 | def DFS(self,s): 38 | visited = set() 39 | stack = [] 40 | stack.append(s) 41 | 42 | while (len(stack)): 43 | s=stack.pop() 44 | if s not in visited: 45 | print(s,end=' ') 46 | visited.add(s) 47 | 48 | for node in self.graph[s]: 49 | if node not in visited: 50 | stack.append(node) 51 | 52 | 53 | V = 6 54 | graph = Graph(V) 55 | graph.add_edge('R', 'M') 56 | graph.add_edge('M', 'N') 57 | graph.add_edge('M', 'Q') 58 | graph.add_edge('Q', 'P') 59 | graph.add_edge('N', 'O') 60 | graph.add_edge('O', 'P') 61 | graph.add_edge('N', 'Q') 62 | print('Breath First Search: ',end='') 63 | graph.BFS('Q') 64 | print() 65 | print('Depth First Search: ',end='') 66 | graph.DFS('Q') 67 | 68 | ##OUTPUT: 69 | ''' 70 | Breath First Search: Q M P N R O 71 | Depth First Search: Q N O P M R 72 | 73 | ''' 74 | -------------------------------------------------------------------------------- /Dijkstra's Algorithm.py: -------------------------------------------------------------------------------- 1 | class Graph: 2 | def __init__(self, vertices): 3 | self.V = vertices 4 | self.graph = {} 5 | self.blocked=[] 6 | 7 | 8 | def add_edge(self, src, dest,weight): 9 | 10 | if self.graph.get(src) == None: 11 | self.graph[src]=[(dest,weight)] 12 | else: 13 | self.graph[src]=self.graph.get(src)+[(dest,weight)] 14 | 15 | 16 | def dijkstra(self,src, dst=None): 17 | 18 | vertices = [] 19 | for n in self.graph: 20 | vertices.append(n) 21 | for v in self.graph[n]: 22 | vertices +=[v[0]] 23 | 24 | queue = set(vertices) 25 | vertices = list(queue) 26 | 27 | dist = {} 28 | prev = {} 29 | for n in vertices: 30 | dist[n] = float('inf') 31 | prev[n] = None 32 | 33 | dist[src] = 0 34 | 35 | while queue: 36 | u = min(queue, key=dist.get) 37 | queue.remove(u) 38 | 39 | if dst is not None and u == dst: 40 | return dist[dst], prev 41 | 42 | for v, w in self.graph.get(u, ()): 43 | if v in self.blocked: 44 | w=float('inf') 45 | alt = dist[u] + w 46 | if alt < dist[v]: 47 | dist[v] = alt 48 | prev[v] = u 49 | 50 | return dist, prev 51 | 52 | def find_path(self,pr, vert): 53 | rev = [] 54 | while vert is not None: 55 | rev.append(vert) 56 | vert = pr[vert] 57 | return rev[::-1] 58 | 59 | def add_blocked(self,bl): 60 | self.blocked=bl 61 | 62 | dest_names={ 63 | 0:'Mouchak',1:'Panthapath',2:'Rampura',3:'Shahbagh', 64 | 4:'Dhanmondi',5:'Lalmatia',6:'Badda',7:'Hatirjheel', 65 | 8:'Nilkhet',9:'TSC',10:'Dhaka University',11:'BUET' 66 | } 67 | 68 | N=int(input()) 69 | M=int(input()) 70 | 71 | myGraph = Graph(N) 72 | 73 | for i in range(M): 74 | u,v,w = map(int,input().split()) 75 | #u,v = map(str,input().split()) ##to take string values 76 | #w=int(input()) 77 | myGraph.add_edge(u, v,w) 78 | 79 | src=int(input()) ## remove int() to take string values 80 | dest=int(input()) ## remove int() to take string values 81 | 82 | blocked= list(map(int,input().split())) ## remove int() to take string values 83 | 84 | myGraph.add_blocked(blocked) 85 | 86 | cost, prev = myGraph.dijkstra(src, dest) 87 | path = myGraph.find_path(prev, dest) 88 | 89 | 90 | for i in path: 91 | if i==path[0]: 92 | print("{}".format(dest_names[i]), end="") 93 | else: 94 | print("->{}".format(dest_names[i]), end="") 95 | print() 96 | print("Path cost: {}".format(cost)) 97 | 98 | 99 | ## INPUT: 100 | ''' 101 | 12 102 | 16 103 | 0 1 5 104 | 0 2 2 105 | 0 3 10 106 | 1 4 20 107 | 1 5 10 108 | 2 6 3 109 | 2 7 12 110 | 3 8 5 111 | 3 9 8 112 | 4 11 5 113 | 5 10 6 114 | 7 8 2 115 | 8 10 10 116 | 8 11 12 117 | 9 11 2 118 | 11 10 2 119 | 0 120 | 10 121 | 2 5 6 8 122 | 123 | ''' 124 | 125 | ## OUTPUT: 126 | 127 | ''' 128 | Mouchak->Shahbagh->TSC->BUET->Dhaka University 129 | Path cost: 22 130 | 131 | ''' 132 | -------------------------------------------------------------------------------- /Undirected Graph Representations.py: -------------------------------------------------------------------------------- 1 | class Graph: 2 | def __init__(self, vertices): 3 | self.V = vertices 4 | self.graph = {} 5 | 6 | self.matrix = [] 7 | for i in range(self.V): 8 | self.matrix.append([0 for i in range(self.V)]) 9 | 10 | def add_edge(self, src, dest): 11 | 12 | ##for adjacency list 13 | 14 | if self.graph.get(src) == None: 15 | self.graph[src]=[dest] 16 | else: 17 | self.graph[src]=self.graph.get(src)+[dest] 18 | 19 | if self.graph.get(dest) == None: 20 | self.graph[dest]=[src] 21 | else: 22 | self.graph[dest]=self.graph.get(dest)+[src] 23 | 24 | ##for adjacency matrix 25 | 26 | key_list=list(self.graph.keys()) 27 | 28 | i1 = key_list.index(src) 29 | i2 = key_list.index(dest) 30 | self.matrix[i1][i2] = 1 31 | self.matrix[i2][i1] = 1 32 | 33 | def print_adj_list(self): 34 | print("Adjacency List: ") 35 | print() 36 | for i in self.graph: 37 | print("Adjacency list of vertex: {}\n head ".format(i), end="") 38 | for j in self.graph[i]: 39 | print(" -> {}".format(j), end="") 40 | print(' \n') 41 | 42 | 43 | def print_adj_matrix(self): 44 | print("Adjacency Matrix: ") 45 | print() 46 | for i in self.matrix: 47 | print(i) 48 | 49 | 50 | 51 | 52 | V = 5 53 | graph = Graph(V) 54 | graph.add_edge(0, 1) 55 | graph.add_edge(0, 2) 56 | graph.add_edge(1, 2) 57 | graph.add_edge(1, 3) 58 | graph.add_edge(2, 3) 59 | graph.add_edge(2, 4) 60 | graph.add_edge(3, 4) 61 | graph.print_adj_list() 62 | graph.print_adj_matrix() 63 | print() 64 | print("---------------------------") 65 | print() 66 | V = 5 67 | graph = Graph(V) 68 | graph.add_edge('A', 'B') 69 | graph.add_edge('A', 'C') 70 | graph.add_edge('B', 'C') 71 | graph.add_edge('B', 'D') 72 | graph.add_edge('C', 'D') 73 | graph.add_edge('C', 'E') 74 | graph.add_edge('D', 'E') 75 | graph.print_adj_list() 76 | graph.print_adj_matrix() 77 | 78 | 79 | ## OUTPUT: 80 | ''' 81 | 82 | Adjacency List: 83 | 84 | Adjacency list of vertex: 0 85 | head -> 1 -> 2 86 | 87 | Adjacency list of vertex: 1 88 | head -> 0 -> 2 -> 3 89 | 90 | Adjacency list of vertex: 2 91 | head -> 0 -> 1 -> 3 -> 4 92 | 93 | Adjacency list of vertex: 3 94 | head -> 1 -> 2 -> 4 95 | 96 | Adjacency list of vertex: 4 97 | head -> 2 -> 3 98 | 99 | Adjacency Matrix: 100 | 101 | [0, 1, 1, 0, 0] 102 | [1, 0, 1, 1, 0] 103 | [1, 1, 0, 1, 1] 104 | [0, 1, 1, 0, 1] 105 | [0, 0, 1, 1, 0] 106 | 107 | --------------------------- 108 | 109 | Adjacency List: 110 | 111 | Adjacency list of vertex: A 112 | head -> B -> C 113 | 114 | Adjacency list of vertex: B 115 | head -> A -> C -> D 116 | 117 | Adjacency list of vertex: C 118 | head -> A -> B -> D -> E 119 | 120 | Adjacency list of vertex: D 121 | head -> B -> C -> E 122 | 123 | Adjacency list of vertex: E 124 | head -> C -> D 125 | 126 | Adjacency Matrix: 127 | 128 | [0, 1, 1, 0, 0] 129 | [1, 0, 1, 1, 0] 130 | [1, 1, 0, 1, 1] 131 | [0, 1, 1, 0, 1] 132 | [0, 0, 1, 1, 0] 133 | 134 | ''' 135 | --------------------------------------------------------------------------------