最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

python編寫的最短路徑算法

 更新時間:2015年03月25日 08:56:10   投稿:hebedich  
本文給大家分享的是python 無向圖最短路徑算法:請各位大大指教,繼續(xù)改進(jìn)。(修改了中文字符串,使py2exe中文沒煩惱),需要的朋友可以參考下

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

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

A ——> 0

B——> 1

C——> 2

D——>3

E——> 4

F——> 5

G——> 6

鄰接矩陣表示無向圖:

算法思想是通過Dijkstra算法結(jié)合自身想法實現(xiàn)的。大致思路是:從起始點(diǎn)開始,搜索周圍的路徑,記錄每個點(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)值和來源節(jié)點(diǎn),否則什么都不做;如果不存在與表B,則添加節(jié)點(diǎn)和權(quán)值和來源節(jié)點(diǎn)到表A,直到搜索到終點(diǎn)則結(jié)束。

這時最短路徑存在于表A中,得到終點(diǎn)的權(quán)值和來源路徑,向上遞推到起始點(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]): # 對節(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_list
def 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)] = val
if __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é)果:

再來一例:

<!-- lang: python -->
# -*- coding: utf-8 -*-
import itertools
import re
import math

def combination(lst):  #全排序
  lists=[]
  liter=itertools.permutations(lst)
  for lts in list(liter):
    lt=''.join(lts)
    lists.append(lt)
  return lists

def coord(lst):   #坐標(biāo)輸入
  coordinates=dict()
  print u'請輸入坐標(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 coordinates

def 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 lst

def count(lst,coordinates): #計算各路徑
  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 way

if __name__ =="__main__":
  print u'請輸入圖節(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"

#無方向完全圖
  list_directive=repeat(list_directive)
  list_directive=repeat(list_directive)
#  print "無方向完全圖所有路徑為:",list_directive
  print u'無方向完全圖所有路徑為:'
  for it in list_directive:
    print it
  print u'無方向完全圖所有路徑總數(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()

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

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

相關(guān)文章

  • Pygame實戰(zhàn)練習(xí)之推箱子游戲

    Pygame實戰(zhàn)練習(xí)之推箱子游戲

    推箱子想必是很多人童年時期的經(jīng)典游戲,我們依舊能記得抱個老人機(jī)娛樂的場景,下面這篇文章主要給大家介紹了關(guān)于如何利用python寫一個簡單的推箱子小游戲的相關(guān)資料,需要的朋友可以參考下
    2021-09-09
  • python獲取外網(wǎng)ip地址的方法總結(jié)

    python獲取外網(wǎng)ip地址的方法總結(jié)

    這篇文章主要介紹了python獲取外網(wǎng)ip地址的方法,實例總結(jié)了四種常用的獲取外網(wǎng)IP地址的技巧,需要的朋友可以參考下
    2015-07-07
  • Python基于多線程實現(xiàn)ping掃描功能示例

    Python基于多線程實現(xiàn)ping掃描功能示例

    這篇文章主要介紹了Python基于多線程實現(xiàn)ping掃描功能,結(jié)合實例形式分析了Python多線程與進(jìn)程相關(guān)模塊調(diào)用操作技巧,需要的朋友可以參考下
    2018-07-07
  • python讓函數(shù)不返回結(jié)果的方法

    python讓函數(shù)不返回結(jié)果的方法

    在本篇內(nèi)容里小編給大家整理的是關(guān)于python讓函數(shù)不返回結(jié)果的方法,有需要的朋友們可以參考下。
    2020-06-06
  • 聊聊prod()與cumprod()區(qū)別cumsum()

    聊聊prod()與cumprod()區(qū)別cumsum()

    這篇文章主要介紹了prod()與cumprod()區(qū)別cumsum(),具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2021-05-05
  • Python字符串處理函數(shù)簡明總結(jié)

    Python字符串處理函數(shù)簡明總結(jié)

    這篇文章主要介紹了Python字符串處理函數(shù)簡明總結(jié),本文總結(jié)了一些常用的字符串處理函數(shù),需要的朋友可以參考下
    2015-04-04
  • python遍歷字符串中每一個字符的4種方式

    python遍歷字符串中每一個字符的4種方式

    很多計算過程都需要每次從一個字符串中取一個字符,下面這篇文章主要給大家介紹了關(guān)于python遍歷字符串中每一個字符的4種方式,文中通過實例代碼介紹的非常詳細(xì),需要的朋友可以參考下
    2023-05-05
  • python模塊導(dǎo)入的細(xì)節(jié)詳解

    python模塊導(dǎo)入的細(xì)節(jié)詳解

    這篇文章主要給大家介紹了關(guān)于python模塊導(dǎo)入細(xì)節(jié)的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2018-12-12
  • Python Scapy隨心所欲研究TCP協(xié)議棧

    Python Scapy隨心所欲研究TCP協(xié)議棧

    今天小編就為大家分享一篇關(guān)于Python Scapy隨心所欲研究TCP協(xié)議棧,小編覺得內(nèi)容挺不錯的,現(xiàn)在分享給大家,具有很好的參考價值,需要的朋友一起跟隨小編來看看吧
    2018-11-11
  • Keras搭建M2Det目標(biāo)檢測平臺示例

    Keras搭建M2Det目標(biāo)檢測平臺示例

    這篇文章主要為大家介紹了Keras搭建M2Det目標(biāo)檢測平臺實現(xiàn)的源碼示例,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2022-05-05

最新評論

新蔡县| 长岭县| 云浮市| 广丰县| 赤城县| 奇台县| 阜平县| 开化县| 斗六市| 铜山县| 吉安市| 金堂县| 芒康县| 尼木县| 福海县| 伊宁县| 桃园县| 买车| 灵丘县| 天镇县| 莎车县| 岐山县| 内黄县| 南靖县| 巴林左旗| 开鲁县| 宜宾市| 洞口县| 逊克县| 天峻县| 绿春县| 金溪县| 革吉县| 淅川县| 静乐县| 定安县| 海林市| 江达县| 阿瓦提县| 清河县| 新乡县|