[英]How to find minimum spanning tree connecting a set of co-ordinates in the 2d plane?
I have already coded Prim's algorithm in python, but this takes as inputs a weighted graph with nodes and edges, which is not what i have. 我已经用python编码了Prim的算法,但这是以节点和边的加权图作为输入的,这不是我所拥有的。
How do I convert the given co-ordinates in to a graph such that the program can accept the inputs, and i get a meaningful answer? 如何将给定的坐标转换为图形,以便程序可以接受输入,并且得到有意义的答案?
This is where the concept of Classes shall prove useful. 在这里,类的概念将被证明是有用的。
Create a Coordinate class and store your nodes and edges as instances of that class. 创建一个Coordinate类,并将节点和边存储为该类的实例。 Add a __sub__ method to the Coordinate class so as to get the Weights (Distances or whatever you want weights to be.) between two Coordinates. 将__sub__方法添加到Coordinate类中,以获取两个Coordinates之间的权重(距离或任何您希望的权重。)。
Example :- 例子:-
class Coordinate:
def __init__(self, x, y):
self.x = x
self.y = y
def __sub__(self, other):
return (self.x - other.x)**2 + (self.y - other.y)**2
# No need to square root to compare distances.
Now you can easily create an Adjacency Map/List as per your convenience and also find the corresponding weights and use your algorithm. 现在,您可以根据需要轻松创建邻接图/列表,还可以找到相应的权重并使用算法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.