davegimo

dfs

Sep 19th, 2022
952
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.02 KB | None | 0 0
  1. #--- LEZIONE 24 (19 maggio 2020)  ---
  2. #--- DFS Visita in profondità di un grafo
  3.  
  4. #--- CREA GRAFO ---
  5.  
  6. inf = float("inf")
  7.  
  8. def createGraph(n):
  9.     G = []
  10.     for i in range(n):
  11.         G.append([])
  12.     return G
  13.  
  14. def size(G):
  15.     return len(G)
  16.  
  17. def printGraph(G):
  18.     for i in range(len(G)):
  19.         print(G[i])
  20.  
  21. #--- theta(1) ---
  22. def insert(G,i,j,w):
  23.     if not isEdge(G,i,j):
  24.         G[i].append([j,w])
  25.  
  26. #--- theta(n) ---
  27. def delete(G,i,j):
  28.     for k in range(len(G[i])):
  29.         if G[i][k][0] == j:
  30.             G[i].pop(k)
  31.  
  32. #--- theta(n) ---
  33. def isEdge(G,i,j):
  34.     for k in range(len(G[i])):
  35.         if G[i][k][0] == j:
  36.             return True
  37.     return False
  38.  
  39. #--- theta(n) ---
  40. def weight(G,i,j):
  41.     for k in range(len(G[i])):
  42.         if G[i][k][0] == j:
  43.             return G[i][k][1]
  44.     return inf
  45.  
  46. def outDegree(G,i):
  47.     return len(G[i])
  48.  
  49. #--- theta(1) ---
  50. def neighbors(G,i):
  51.     return G[i]
  52.  
  53. #--- theta(n) ---
  54. def neighborsCopy(G,i):
  55.     V = []
  56.     for [j,w] in G[i]:
  57.         V.append(j)
  58.     return V
  59.  
  60. #---------- Programma principale ------------
  61.  
  62. G = createGraph(10)
  63.  
  64. insert(G, 0, 1, 1)
  65. insert(G, 0, 4, 1)
  66. insert(G, 0, 5, 1)
  67. insert(G, 1, 2, 1)
  68. insert(G, 2, 3, 1)
  69. #insert(G, 3, 1, 1)
  70. insert(G, 4, 5, 1)
  71. insert(G, 4, 6, 1)
  72. insert(G, 4, 7, 1)
  73. insert(G, 4, 8, 1)
  74. insert(G, 6, 5, 1)
  75. insert(G, 7, 8, 1)
  76. insert(G, 8, 9, 1)
  77. insert(G, 9, 7, 1)
  78.  
  79. print("")
  80. print("--- Grafo (Lista di Adiacenza) ---")
  81. printGraph(G)
  82.  
  83. def DFS(Graph,source):
  84.     n = size(Graph)
  85.     reached = []
  86.     for i in range(n):
  87.         reached.append(False)
  88.     reached[source] = True          ## apparecchio le variabili, dicendo che source
  89.     Tree = []                       ## è stata visitata
  90.     DFSV(Graph,source,reached,Tree)
  91.     return Tree
  92.  
  93. def DFSV(Graph,k,reached,Tree):
  94.     V = neighbors(Graph,k)
  95.     for [j,w] in V:
  96.         if reached[j] == False:
  97.             reached[j] = True
  98.             Tree.append([k,j])
  99.             DFSV(Graph,j,reached,Tree)
  100.  
  101. print("")
  102. print("DFS: ", DFS(G,0))
Advertisement
Add Comment
Please, Sign In to add comment