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 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116
| class Vertex: def __init__(self, vid, outList): self.vid = vid self.outList = outList self.know = False self.dist = float('inf') self.prev = 0
def __eq__(self, other): if isinstance(other, self.__class__): return self.vid == other.vid else: return False
def __hash__(self): return hash(self.vid)
class graph: def __init__(self, vertex, edges, v_set): self.vlist = vertex self.edges = edges self.vset = v_set
e_dict = dict()
def add_edge(front, back, value): e_dict[(front, back)] = value
v1 = Vertex(1, [2, 4]) v2 = Vertex(2, [4, 5]) v3 = Vertex(3, [1, 6]) v4 = Vertex(4, [3, 5, 6, 7]) v5 = Vertex(5, [7]) v6 = Vertex(6, []) v7 = Vertex(7, [6]) add_edge(1, 2, 2) add_edge(1, 4, 1) add_edge(3, 1, 4) add_edge(4, 3, 2) add_edge(2, 4, 3) add_edge(2, 5, 10) add_edge(4, 5, 2) add_edge(3, 6, 5) add_edge(4, 6, 8) add_edge(4, 7, 4) add_edge(7, 6, 1) add_edge(5, 7, 6) v_list = [False, v1, v2, v3, v4, v5, v6, v7] vset = set([v1, v2, v3, v4, v5, v6, v7]) g = graph(v_list, e_dict, vset)
def get_unknown_min(): the_min = 0 the_index = 0 j = 0 for i in range(1, len(g.vlist)): if (g.vlist[i].know is True): continue else: if (j == 0): the_min = g.vlist[i].dist the_index = i else: if (g.vlist[i].dist < the_min): the_min = g.vlist[i].dist the_index = i j += 1 vset.remove(g.vlist[the_index]) return g.vlist[the_index]
def main(): v1.dist = 0
while (len(vset) != 0): v = get_unknown_min() print(v.vid, v.dist, v.outList) v.know = True for w in v.outList: if (g.vlist[w].know is True): continue if (g.vlist[w].dist == float('inf')): g.vlist[w].dist = v.dist + g.edges[(v.vid, w)] g.vlist[w].prev = v.vid else: if ((v.dist + g.edges[(v.vid, w)]) < g.vlist[w].dist): g.vlist[w].dist = v.dist + g.edges[(v.vid, w)] g.vlist[w].prev = v.vid else: pass
def real_get_traj(start, index): traj_list = []
def get_traj(index): if (index == start): traj_list.append(index) print(traj_list[::-1]) return if (g.vlist[index].dist == float('inf')): print('从起点到该顶点根本没有路径') return traj_list.append(index) get_traj(g.vlist[index].prev)
get_traj(index) print('该最短路径的长度为', g.vlist[index].dist)
if __name__ == '__main__': main() real_get_traj(1, 3) real_get_traj(1, 6)
|