#初始化 end += 1 table[startPoint] = True queue[end] = startPoint
while start <= end: for i inrange(end - start + 1): cur = queue[start] start += 1 graph[cur] = layer for i inrange(self.size): if self.arr[cur][i] != self.maxNum andnot table[i]: end += 1 queue[end] = i table[i] = True layer += 1 return graph
defdellmanFord(self,startPoint = 0): graph = [] for i inrange(self.size): for j inrange(self.size): if self.arr[i][j] != self.maxNum: graph.append([i,j,self.arr[i][j]]) dist = [self.maxNum] * (self.size) dist[startPoint] = 0 flag = True for i inrange(self.size - 1): flag = True for j inrange(len(graph)): if dist[graph[j][1]] > dist[graph[j][0]] + graph[j][2]: dist[graph[j][1]] = dist[graph[j][0]] + graph[j][2] flag = False if flag: break flag = False for j inrange(len(graph)): if dist[graph[j][1]] > dist[graph[j][0]] + graph[j][2]: flag = True return dist,flag
Floyd算法 (带权图、无权图、无负环、各个顶点之间的最短路径)
用一个新的数组来记录当前状态:
graph(i,j):表示从i到j的最短距离
graph(i,j) = min(graph(i,j) , graph(i,k) + graph(k,j)):表示从i -> k -> j 这条路比 i -> j 这条路短
1 2 3 4 5 6 7 8
deffloyd(self): graph = self.arr.copy() for k inrange(self.size): for i inrange(self.size): for j inrange(self.size): if i != j and graph[i][j] > graph[i][k] + graph[k][j]: graph[i][j] = graph[i][k] + graph[k][j] return graph