Browse Source

add dijcstra

jezvgg 6 months ago
parent
commit
5e6f532bf6
2 changed files with 27 additions and 6 deletions
  1. 21 0
      deikstra.py
  2. 6 6
      graph.py

+ 21 - 0
deikstra.py

@@ -0,0 +1,21 @@
+from graph import Graph
+import numpy as np
+
+graph = Graph.build([[0, 10, 30, 50, 10],
+                     [0, 0, 0, 0, 0],
+                     [0, 0, 0, 0, 10],
+                     [0, 40, 20, 0, 0],
+                     [10, 0, 10, 30, 0]])
+
+weights = np.zeros(len(graph.verticles))
+verticles_weights = weights.copy()
+verticles_weights[1:] = np.inf
+
+while verticles_weights[np.isnan(verticles_weights) == False].shape[0] != 0:
+    current_node = np.nanargmin(verticles_weights)
+    new_weights = graph.matrix[current_node] + verticles_weights[current_node]
+    logical = np.logical_and(verticles_weights > new_weights, new_weights != verticles_weights[current_node])
+    verticles_weights[logical] = new_weights[logical]
+    weights[current_node], verticles_weights[current_node] = verticles_weights[current_node], np.nan
+
+print(weights)

+ 6 - 6
graph.py

@@ -131,7 +131,7 @@ class Graph:
 
         if not isinstance(self.verticles[0], verticle):
             print("Перепись " + "="*32)
-            space = np.linspace(0, 2*np.pi, len(self.verticles)+1)[:-1]
+            space = np.linspace(np.pi/2, 2*np.pi+np.pi/2, len(self.verticles)+1)[:-1]
             self.__verticles = [verticle(name, np.cos(sp)+x, np.sin(sp)+y) for name, sp in zip(self.verticles, space)]
 
         print([vert.name for vert in self.verticles])
@@ -201,11 +201,11 @@ if __name__ == "__main__":
     # print("Invert G1:",~g)
     # g.plot(1, 1)
     # h.plot(3.2, 1)
-    g = Graph.build([[0, 1, 1, 1, 1],
-                     [1, 0, 0, 0, 0],
-                     [1, 0, 0, 1, 1],
-                     [1, 0, 1, 0, 0],
-                     [1, 0, 1, 0, 0]])
+    g = Graph.build([[0, 10, 30, 50, 10],
+                     [0, 0, 0, 0, 0],
+                     [0, 0, 0, 0, 10],
+                     [0, 40, 20, 0, 0],
+                     [10, 0, 10, 30, 0]])
     print(repr(g.graph_type))
     g.plot()
     print(g)