Example #1
0
 def add_edge(self, vi, vj, val=1):
     if self._vnum == 0:
         raise GraphError("Cannot add edge to empty graph.")
     if self._invalid(vi) or self._invalid(vj):
         raise GraphError("{} or {} is not a valid vertex".format(vi, vj))
     row = self._mat[vi]
     i = 0
     while i < len(row):
         if row[i][0] == vj:  # 如果原图存在 vi 到 vj 的边,则用新的 vi 到 vj 的权值覆盖掉原有的权值
             self._mat[vi][i] = (vj, val)  # 修改 mat[vi][vj] 的权值
             return
         if row[i][0] > vj:  # 如果原图中没有到vj的边,跳出循环后加入此边
             break
         i += 1
     self._mat[vi].insert(i, (vj, val))
Example #2
0
 def get_edge(self, vi, vj):
     if self._invalid(vi) or self._invalid(vj):
         raise GraphError("{} or {} is not a valid vertex".format(vi, vj))
     for i, val in self._mat[vi]:
         if i == vj:
             return val
     return self._unconn
Example #3
0
 def __init__(self, mat=None, unconn=0):
     if mat is None:
         mat = []
     vnum = len(mat)
     for x in mat:
         if len(x) != vnum:  # 行数与列数做对比,检查邻接矩阵是否为合法的方阵
             raise GraphError("Argument for 'Graph'.")
     self._mat = [self._out_edges(mat[i], unconn) for i in range(vnum)]
     self._vnum = vnum
     self._unconn = unconn
Example #4
0
    def __init__(self, mat, unconn=0):
        """
		构造方法
		:param mat: 邻接矩阵,嵌套列表
		:param unconn: 无关联情况的特殊值,默认为0
		"""
        vnum = len(mat)  # 获取邻接矩阵行数
        for x in mat:
            if len(x) != vnum:  # 行数与列数做对比,检查邻接矩阵是否为合法的方阵
                raise GraphError("Argument for 'Graph'.")
        self._mat = [mat[i][:] for i in range(vnum)]  # 拷贝
        self._unconn = unconn
        self._vnum = vnum  # 邻接矩阵维数
Example #5
0
 def out_edges(self, vi):
     if self._invalid(vi):
         raise GraphError("{} is not a valid vertex.".format(vi))
     return self._out_edges(self._mat[vi], self._unconn)
Example #6
0
 def get_edge(self, vi, vj):
     if self._invalid(vi) or self._invalid(vj):
         raise GraphError("{} or {} is not a valid vertex".format(vi, vj))
     return self._mat[vi][vj]
Example #7
0
 def add_edge(self, vi, vj, val=1):
     if self._invalid(vi) or self._invalid(vj):
         raise GraphError("{} or {} is not a valid vertex".format(vi, vj))
     self._mat[vi][vj] = val
Example #8
0
 def add_vertex(self):
     raise GraphError("Adj-Matrix does not support 'add_vertex()'.")