1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94
| import numpy as np
class Graph(object):
def __init__(self, maps): self.maps = maps self.nodenum = self.get_nodenum() self.edgenum = self.get_edgenum() def get_nodenum(self): return len(self.maps) def get_edgenum(self): count = 0 for i in range(self.nodenum): for j in range(i): if self.maps[i][j] > 0 and self.maps[i][j] < 9999: count += 1 return count def kruskal(self): res = [] if self.nodenum <= 0 or self.edgenum < self.nodenum-1: return res edge_list = [] for i in range(self.nodenum): for j in range(i, self.nodenum): if self.maps[i][j] < 9999: edge_list.append([i, j, self.maps[i][j]]) edge_list.sort(key=lambda a:a[2]) group = [[i] for i in range(self.nodenum)]
for edge in edge_list: for i in range(len(group)): if edge[0] in group[i]: m = i if edge[1] in group[i]: n = i if m != n: res.append(edge) group[n] = group[m] + group[n] group[m] = [] return res def prim(self): res = [] if self.nodenum <= 0 or self.edgenum < self.nodenum-1: return res res = [] seleted_node = [0] candidate_node = [i for i in range(1, self.nodenum)] while len(candidate_node) > 0: begin, end, minweight = 0, 0, 9999 for i in seleted_node: for j in candidate_node: if self.maps[i][j] < minweight: minweight = self.maps[i][j] begin = i end = j res.append([begin, end, minweight]) seleted_node.append(end) candidate_node.remove(end) return res
if __name__ == '__main__': maps = [ [0, 7, 100, 3, 100, 5], [7, 0, 9, 100, 3, 100], [100, 9, 0, 6, 100, 4], [3, 100, 6, 0, 8, 10], [100, 3, 100, 8, 0, 4], [5, 100 ,4, 10, 4, 0] ]
graph = Graph(maps) print('邻接矩阵为\n%s'%np.array(graph.maps)) print('节点数据为%d,边数为%d\n'%(graph.nodenum, graph.edgenum)) print('---------------------Kruskal---------------------') print(graph.kruskal()) print('---------------------Prim------------------------') print(graph.prim())
|