Advertisement
_Mizanur

artificial

Feb 12th, 2022
1,105
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.58 KB | None | 0 0
  1. # 1.DFS
  2. graph={
  3.     'A':['B','S'],
  4.     'B':['A'],
  5.     'C':['S'],
  6.     'D':['S','F'],
  7.     'E':['S'],
  8.     'F':['D','G'],
  9.     'G':['F'],
  10.     'S':['A','C','D','E']
  11. }
  12. visited=[]
  13. def dfs(graph,visited,node):
  14.     if node not in visited:
  15.         print(node,end=' ')
  16.         visited.append(node)
  17.         for neighbour in graph[node]:
  18.             dfs(graph,visited,neighbour)
  19. dfs(graph,visited,'A')
  20.  
  21. # 2.BFS
  22. graph={
  23.     'A':['B','S'],
  24.     'B':['A'],
  25.     'C':['S'],
  26.     'D':['S','F'],
  27.     'E':['S'],
  28.     'F':['D','G'],
  29.     'G':['F'],
  30.     'S':['A','C','D','E']
  31. }
  32. visited=[]
  33. queue=[]
  34. def bfs(graph,visited,node):
  35.     visited.append(node)
  36.     queue.append(node)
  37.     while queue:
  38.         s=queue.pop(0)
  39.         print(s,end=' ')
  40.         for neighbour in graph[s]:
  41.             if neighbour not in visited:
  42.                 visited.append(neighbour)
  43.                 queue.append(neighbour)
  44. bfs(graph,visited,'A')
  45.  
  46. # 3.TOH
  47. def TOH(n,from_rod,aux_rod,to_rod):
  48.     if(n>0):
  49.         TOH(n-1,from_rod,to_rod,aux_rod)
  50.         print("Move disk ",n," from rod",from_rod," to rod ",to_rod)
  51.         TOH(n-1,aux_rod,from_rod,to_rod)
  52.  
  53. n=int(input("Enter how many disk:"))
  54. TOH(n,'A','B','C')
  55.  
  56. # 4.TSP
  57. graph=[[0,16,11,6],
  58.        [8,0,13,16],
  59.        [4,7,0,9],
  60.        [5,12,2,0]
  61.        ]
  62. n=4
  63. visited=(1<<n)-1
  64. def TSP(mask,pos):
  65.     if(mask==visited):
  66.         return graph[pos][0]
  67.     ans=9999999999
  68.     for city in range(n):
  69.         if((mask&(1<<city))==0):
  70.             newAns=graph[pos][city]+TSP(mask|(1<<city),city)
  71.             ans=min(ans,newAns)
  72.     return ans
  73.  
  74. print(TSP(1,0))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement