一区二区三区在线-一区二区三区亚洲视频-一区二区三区亚洲-一区二区三区午夜-一区二区三区四区在线视频-一区二区三区四区在线免费观看

腳本之家,腳本語言編程技術及教程分享平臺!
分類導航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|

服務器之家 - 腳本之家 - Python - python編寫的最短路徑算法

python編寫的最短路徑算法

2020-05-24 10:29腳本之家 Python

本文給大家分享的是python 無向圖最短路徑算法:請各位大大指教,繼續改進。(修改了中文字符串,使py2exe中文沒煩惱),需要的朋友可以參考下

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

python編寫的最短路徑算法

其中對應索引:

A ——> 0

B——> 1

C——> 2

D——>3

E——> 4

F——> 5

G——> 6

鄰接矩陣表示無向圖:

python編寫的最短路徑算法

算法思想是通過Dijkstra算法結合自身想法實現的。大致思路是:從起始點開始,搜索周圍的路徑,記錄每個點到起始點的權值存到已標記權值節點字典A,將起始點存入已遍歷列表B,然后再遍歷已標記權值節點字典A,搜索節點周圍的路徑,如果周圍節點存在于表B,比較累加權值,新權值小于已有權值則更新權值和來源節點,否則什么都不做;如果不存在與表B,則添加節點和權值和來源節點到表A,直到搜索到終點則結束。

這時最短路徑存在于表A中,得到終點的權值和來源路徑,向上遞推到起始點,即可得到最短路徑,下面是代碼:

?
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
# -*-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(): # 遍歷已有權值節點
      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]): # 對節點進行遍歷
        # 如果節點在權值節點中并且權值大于新權值
        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] # 更新權值
          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

運行結果:

python編寫的最短路徑算法

再來一例:

?
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
<!-- 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):   #坐標輸入
  coordinates=dict()
  print u'請輸入坐標:(格式為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):  #刪除重復組合
  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'請輸入圖節點:'
  rlist=list(raw_input())
  coordinates=coord(rlist)
 
  list_directive = combination(rlist)
#  print "有方向完全圖所有路徑為:",list_directive
#  for it in list_directive:
#    print it
  print u'有方向完全圖所有路徑總數:',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'無方向完全圖所有路徑總數:',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()

以上就是本文給大家分享的全部內容了,希望大家能夠喜歡,能夠學習python有所幫助。

延伸 · 閱讀

精彩推薦
主站蜘蛛池模板: 日韩 国产 欧美 精品 在线 | 2012年免费中文视频 | 免费一区在线观看 | 国产精品久久久久久久久久久搜索 | 忘忧草在线社区WWW日本直播 | 女班长的放荡日记高h | 都市风流贵妇激情 | 精品国产综合区久久久久久 | 干b视频在线观看 | 日韩精品高清自在线 | 色小孩导航 | 成人福利在线视频免费观看 | 香港三级系列在线播放 | 99re8在这里只有精品23 | 国产成人99精品免费观看 | 9久久9久久精品 | 婷婷综合久久中文字幕 | 九九热综合| 强漂亮白丝女教师小说 | 欧美日韩三区 | 日本videosdesexo乱 | 白丝美女用胸伺候主人 | 美女的隐私脱裤子无遮挡 | 高清不卡日本v在线二区 | 糖心vlog麻豆精东影业传媒 | 国产高清在线视频一区二区三区 | 99re精品在线 | 日本一二线不卡在线观看 | 日韩专区在线观看 | 99视频精品全部免费观看 | 四虎永久免费地址在线网站 | 午夜影院和视费x看 | 国产午夜成人无码免费看 | juy799大岛优香在线观看 | 日本videossexx日本人 | 国内精品免费 | 国内老司机精品视频在线播出 | 久久天堂成人影院 | 第一次不是你高清在线观看 | yellow最新视频2019 | 亚洲日韩欧美一区二区在线 |