我试图从邻接表中创建一个无向图来练习Karger的最小切割算法。下面是我的代码从邻接表中创建无向图
class Vertex(object):
'''Represents a vertex, with the indices of edges
incident on it'''
def __init__(self,name,edgeIndices=[]):
self.name = name
self.edgeIndices = edgeIndices
def getName(self):
return self.name
def addEdge(self,ind):
self.edgeIndices.append(ind)
def getEdges(self):
return self.edgeIndices
def __eq__(self,other):
return self.name == other.name
class Edge(object):
'''Represents an edge with the indices of its endpoints'''
def __init__(self,ends):
self.ends = ends
def getEnds(self):
return self.ends
def __eq__(self,other):
return (self.ends == other.ends)\
or ((self.ends[1],self.ends[0]) == other.ends)
class Graph(object):
def __init__(self,vertices,edges):
self.edges = edges
self.vertices = vertices
def createGraph(filename):
'''Input: Adjacency list
Output: Graph object'''
vertices = []
edges = []
with open(filename) as f:
for line in f:
elements = line.split()
newVert = Vertex(elements[0])
if newVert not in vertices:
vertices.append(newVert)
for verts in elements[1:]:
otherVert = Vertex(verts)
if otherVert not in vertices:
vertices.append(otherVert)
end1 = vertices.index(newVert)
end2 = vertices.index(otherVert)
newEdge = Edge((end1,end2))
if newEdge not in edges:
edges.append(newEdge)
newVert.addEdge(edges.index(newEdge))
return Graph(vertices,edges)
假设邻接表是由整数表示顶点如下
1 -> 2,3,4
2 -> 1,3
3 -> 1,2,4
4 -> 1,3
总体而言,该图将有五个棱,所以列表的长度保持边缘指数一个顶点与长度不超过5。例如,我期望顶点'2'具有仅两个边的索引,即具有顶点1和3的边。相反,我得到的是[0, 1, 2, 3, 0, 2, 1, 3]
。 我需要帮助来弄清楚发生了什么问题。
我存储所述顶点和边作为图形对象阵列,然后交叉引用这两个阵列。是否可以对字典执行相同的操作,因为它们可以使用键来访问,而且字典中的条目可能与我们输入的顺序不同。 – dpk
那么,字典的重点是真的加快图形加载和简化代码。如果您的顶点有不连续的标签并需要存储某些映射,则字典和键将变得方便。 –
如果你打算用你的图进行大量计算,那么这些数组应该能够让你更快地访问,并且最终会变得更好。如果您的顶点在文件中标记为1到n,我将按排序顺序填充(n + 1)个顶点的数组,然后添加边。或者将顶点从0标记到(n-1)。在使用索引而不是实际对象时,创建边不需要实际顶点,只需从其标签中扣除其索引即可。 –