国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁(yè) > 編程 > Python > 正文

python編寫的最短路徑算法

2019-11-25 17:54:52
字體:
來(lái)源:轉(zhuǎn)載
供稿:網(wǎng)友

一心想學(xué)習(xí)算法,很少去真正靜下心來(lái)去研究,前幾天趁著周末去了解了最短路徑的資料,用python寫了一個(gè)最短路徑算法。算法是基于帶權(quán)無(wú)向圖去尋找兩個(gè)點(diǎn)之間的最短路徑,數(shù)據(jù)存儲(chǔ)用鄰接矩陣記錄。首先畫出一幅無(wú)向圖如下,標(biāo)出各個(gè)節(jié)點(diǎn)之間的權(quán)值。

其中對(duì)應(yīng)索引:

A ――> 0

B――> 1

C――> 2

D――>3

E――> 4

F――> 5

G――> 6

鄰接矩陣表示無(wú)向圖:

算法思想是通過(guò)Dijkstra算法結(jié)合自身想法實(shí)現(xiàn)的。大致思路是:從起始點(diǎn)開始,搜索周圍的路徑,記錄每個(gè)點(diǎn)到起始點(diǎn)的權(quán)值存到已標(biāo)記權(quán)值節(jié)點(diǎn)字典A,將起始點(diǎn)存入已遍歷列表B,然后再遍歷已標(biāo)記權(quán)值節(jié)點(diǎn)字典A,搜索節(jié)點(diǎn)周圍的路徑,如果周圍節(jié)點(diǎn)存在于表B,比較累加權(quán)值,新權(quán)值小于已有權(quán)值則更新權(quán)值和來(lái)源節(jié)點(diǎn),否則什么都不做;如果不存在與表B,則添加節(jié)點(diǎn)和權(quán)值和來(lái)源節(jié)點(diǎn)到表A,直到搜索到終點(diǎn)則結(jié)束。

這時(shí)最短路徑存在于表A中,得到終點(diǎn)的權(quán)值和來(lái)源路徑,向上遞推到起始點(diǎn),即可得到最短路徑,下面是代碼:

# -*-coding:utf-8 -*-class DijkstraExtendPath():  def __init__(self, node_map):    self.node_map = node_map    self.node_length = len(node_map)    self.used_node_list = []    self.collected_node_dict = {}  def __call__(self, from_node, to_node):    self.from_node = from_node    self.to_node = to_node    self._init_dijkstra()    return self._format_path()  def _init_dijkstra(self):    self.used_node_list.append(self.from_node)    self.collected_node_dict[self.from_node] = [0, -1]    for index1, node1 in enumerate(self.node_map[self.from_node]):      if node1:        self.collected_node_dict[index1] = [node1, self.from_node]    self._foreach_dijkstra()  def _foreach_dijkstra(self):    if len(self.used_node_list) == self.node_length - 1:      return    for key, val in self.collected_node_dict.items(): # 遍歷已有權(quán)值節(jié)點(diǎn)      if key not in self.used_node_list and key != to_node:        self.used_node_list.append(key)      else:        continue      for index1, node1 in enumerate(self.node_map[key]): # 對(duì)節(jié)點(diǎn)進(jìn)行遍歷        # 如果節(jié)點(diǎn)在權(quán)值節(jié)點(diǎn)中并且權(quán)值大于新權(quán)值        if node1 and index1 in self.collected_node_dict and self.collected_node_dict[index1][0] > node1 + val[0]:          self.collected_node_dict[index1][0] = node1 + val[0] # 更新權(quán)值          self.collected_node_dict[index1][1] = key        elif node1 and index1 not in self.collected_node_dict:          self.collected_node_dict[index1] = [node1 + val[0], key]    self._foreach_dijkstra()  def _format_path(self):    node_list = []    temp_node = self.to_node    node_list.append((temp_node, self.collected_node_dict[temp_node][0]))    while self.collected_node_dict[temp_node][1] != -1:      temp_node = self.collected_node_dict[temp_node][1]      node_list.append((temp_node, self.collected_node_dict[temp_node][0]))    node_list.reverse()    return node_listdef set_node_map(node_map, node, node_list):  for x, y, val in node_list:    node_map[node.index(x)][node.index(y)] = node_map[node.index(y)][node.index(x)] = valif __name__ == "__main__":  node = ['A', 'B', 'C', 'D', 'E', 'F', 'G']  node_list = [('A', 'F', 9), ('A', 'B', 10), ('A', 'G', 15), ('B', 'F', 2),         ('G', 'F', 3), ('G', 'E', 12), ('G', 'C', 10), ('C', 'E', 1),         ('E', 'D', 7)]  node_map = [[0 for val in xrange(len(node))] for val in xrange(len(node))]  set_node_map(node_map, node, node_list)  # A -->; D  from_node = node.index('A')  to_node = node.index('D')  dijkstrapath = DijkstraPath(node_map)  path = dijkstrapath(from_node, to_node)  print path

運(yùn)行結(jié)果:

再來(lái)一例:

<!-- lang: python --># -*- coding: utf-8 -*-import itertoolsimport reimport mathdef combination(lst):  #全排序  lists=[]  liter=itertools.permutations(lst)  for lts in list(liter):    lt=''.join(lts)    lists.append(lt)  return listsdef coord(lst):   #坐標(biāo)輸入  coordinates=dict()  print u'請(qǐng)輸入坐標(biāo):(格式為A:7 17)'  p=re.compile(r"/d+")  for char in lst:    str=raw_input(char+':')    dot=p.findall(str)    coordinates[char]=[dot[0],dot[1]]  print coordinates  return coordinatesdef repeat(lst):  #刪除重復(fù)組合  for ilist in lst:    for k in xrange(len(ilist)):      st=(ilist[k:],ilist[:k])      strs=''.join(st)      for jlist in lst:        if(cmp(strs,jlist)==0):          lst.remove(jlist)    for k in xrange(len(ilist)):      st=(ilist[k:],ilist[:k])      strs=''.join(st)      for jlist in lst:        if(cmp(strs[::-1],jlist)==0):          lst.remove(jlist)    lst.append(ilist)    print lst  return lstdef count(lst,coordinates): #計(jì)算各路徑  way=dict()  for str in lst:    str=str+str[:1]    length=0    for i in range(len(str)-1):      x=abs( float(coordinates[str[i]][0]) - float(coordinates[str[i+1]][0]) )      y=abs( float(coordinates[ str[i] ][1]) - float(coordinates[ str[i+1] ][1]) )      length+=math.sqrt(x**2+y**2)    way[str[:len(str)-1]]=length  return wayif __name__ =="__main__":  print u'請(qǐng)輸入圖節(jié)點(diǎn):'  rlist=list(raw_input())  coordinates=coord(rlist)  list_directive = combination(rlist)#  print "有方向完全圖所有路徑為:",list_directive#  for it in list_directive:#    print it  print u'有方向完全圖所有路徑總數(shù):',len(list_directive),"/n"#無(wú)方向完全圖  list_directive=repeat(list_directive)  list_directive=repeat(list_directive)#  print "無(wú)方向完全圖所有路徑為:",list_directive  print u'無(wú)方向完全圖所有路徑為:'  for it in list_directive:    print it  print u'無(wú)方向完全圖所有路徑總數(shù):',len(list_directive)  ways=count(list_directive,coordinates)  print u'路徑排序如下:'  for dstr in sorted(ways.iteritems(), key=lambda d:d[1], reverse = False ):    print dstr  raw_input()

以上就是本文給大家分享的全部?jī)?nèi)容了,希望大家能夠喜歡,能夠?qū)W習(xí)python有所幫助。

請(qǐng)您花一點(diǎn)時(shí)間將文章分享給您的朋友或者留下評(píng)論。我們將會(huì)由衷感謝您的支持!

發(fā)表評(píng)論 共有條評(píng)論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 高阳县| 诏安县| 柏乡县| 思茅市| 南投市| 东明县| 江川县| 平阳县| 石渠县| 凉城县| 五指山市| 麻栗坡县| 区。| 武城县| 邵阳县| 信阳市| 民和| 永顺县| 许昌市| 突泉县| 伽师县| 神农架林区| 丽江市| 济南市| 赤城县| 福建省| 凤山县| 波密县| 甘肃省| 龙胜| 靖宇县| 南康市| 清流县| 凉山| 兰州市| 兴隆县| 左云县| 正安县| 社会| 舒兰市| 灵山县|