Advertisement
chlebq

Untitled

Apr 8th, 2020
681
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.89 KB | None | 0 0
  1. class node:
  2.     def __init__(self, n):
  3.         self.parent = None
  4.         self.d = 0
  5.         self.visited = False
  6.         self.numer = n
  7.  
  8. class queue:
  9.     def __init__(self):
  10.         self.arr = []
  11.         self.elements = 0
  12.         self.head = 0
  13.  
  14.     def put(self, val):
  15.         self.arr.append(val)
  16.         self.elements += 1
  17.  
  18.     def get(self):
  19.         res = self.arr[self.head]
  20.         self.head += 1
  21.         self.elements -= 1
  22.         return res
  23.  
  24.     def is_empty(self):
  25.         if self.elements == 0:
  26.             return True
  27.         return False
  28.  
  29.  
  30.  
  31.  
  32. def BFS(G, s):
  33.         # G -> macierz opisująca graf G: G[i][j]==1 jeśli jest
  34.         # wierzchołek z i do j. W przeciwnym razie G[i][j]=0
  35.         # s to numer wierzchołka źródłowego
  36.         n = len(G)
  37.         Q = queue()  # nasza kolejka
  38.  
  39.         # teraz musimy jakos wierzcholki zareprezentowac:
  40.         N = [0] * n  # lista wierzcholków
  41.         for i in range(0, n):
  42.             N[i] = node(i)  # ustawiamy jak na wykładzie
  43.  
  44.         Q.put(N[s])
  45.  
  46.         while not Q.is_empty():
  47.             u = Q.get()
  48.             for v in N:  # lecimy po strukturze wierzchołków
  49.                 if G[u.numer][v.numer] == 1:
  50.                     if not v.visited:
  51.                         v.visited = True
  52.                         v.d = u.d + 1
  53.                         v.parent = u
  54.                         Q.put(v)
  55.  
  56.         maks = 0
  57.         z = 0
  58.         for i in range(0, len(N)):
  59.             if N[i].d > maks:
  60.                 maks = i
  61.                 z = maks
  62.  
  63.         res = [[0, 0]] * (z + 1)
  64.         tmp = node(i)
  65.         tmp = N[z]
  66.         z = z - 1
  67.         while z >= 0:
  68.             y = tmp.parent
  69.             res[z][0] = y.numer
  70.             res[z][1] = tmp.numer
  71.             tmp = tmp.parent
  72.             z -= 1
  73.         return res
  74.  
  75. G = [[0,1,1,0],[0,0,0,1],[0,1,0,1], [0,0,0,0]]
  76.  
  77. print( BFS(G,0) )
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement