python編寫的最短路徑算法
一心想學(xué)習(xí)算法,很少去真正靜下心來去研究,前幾天趁著周末去了解了最短路徑的資料,用python寫了一個(gè)最短路徑算法。算法是基于帶權(quán)無向圖去尋找兩個(gè)點(diǎn)之間的最短路徑,數(shù)據(jù)存儲(chǔ)用鄰接矩陣記錄。首先畫出一幅無向圖如下,標(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
鄰接矩陣表示無向圖:

算法思想是通過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)值和來源節(jié)點(diǎn),否則什么都不做;如果不存在與表B,則添加節(jié)點(diǎn)和權(quán)值和來源節(jié)點(diǎn)到表A,直到搜索到終點(diǎn)則結(jié)束。
這時(shí)最短路徑存在于表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]): # 對(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_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'請(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 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): #計(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 way
if __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"
#無方向完全圖
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()
以上就是本文給大家分享的全部?jī)?nèi)容了,希望大家能夠喜歡,能夠?qū)W習(xí)python有所幫助。
請(qǐng)您花一點(diǎn)時(shí)間將文章分享給您的朋友或者留下評(píng)論。我們將會(huì)由衷感謝您的支持!
- Python數(shù)據(jù)結(jié)構(gòu)與算法之圖的最短路徑(Dijkstra算法)完整實(shí)例
- Python使用Dijkstra算法實(shí)現(xiàn)求解圖中最短路徑距離問題詳解
- python Dijkstra算法實(shí)現(xiàn)最短路徑問題的方法
- Python實(shí)現(xiàn)的多叉樹尋找最短路徑算法示例
- Python實(shí)現(xiàn)最短路徑問題的方法
- python實(shí)現(xiàn)最短路徑的實(shí)例方法
- python3實(shí)現(xiàn)Dijkstra算法最短路徑的實(shí)現(xiàn)
- python3實(shí)現(xiàn)無權(quán)最短路徑的方法
- Python?最短路徑的幾種求解方式
相關(guān)文章
python如何實(shí)現(xiàn)數(shù)組元素兩兩相加
這篇文章主要介紹了python如何實(shí)現(xiàn)數(shù)組元素兩兩相加,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-05-05
Python 結(jié)巴分詞實(shí)現(xiàn)關(guān)鍵詞抽取分析
這篇文章主要介紹了Python 結(jié)巴分詞實(shí)現(xiàn)關(guān)鍵詞抽取分析,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2017-10-10
Python通過Django實(shí)現(xiàn)用戶注冊(cè)和郵箱驗(yàn)證功能代碼
這篇文章主要介紹了Python通過Django實(shí)現(xiàn)用戶注冊(cè)和郵箱驗(yàn)證功能代碼,具有一定借鑒價(jià)值,需要的朋友可以參考下。2017-12-12
PyQT實(shí)現(xiàn)菜單中的復(fù)制,全選和清空的功能的方法
今天小編就為大家分享一篇PyQT實(shí)現(xiàn)菜單中的復(fù)制,全選和清空的功能的方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2019-06-06
pandas如何獲取某個(gè)數(shù)據(jù)的行號(hào)
這篇文章主要介紹了pandas如何獲取某個(gè)數(shù)據(jù)的行號(hào)問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-02-02
python實(shí)現(xiàn)百度文庫自動(dòng)化爬取
項(xiàng)目是合法項(xiàng)目,只是進(jìn)行數(shù)據(jù)解析而已,不能下載看不到的內(nèi)容.部分文檔在電腦端不能預(yù)覽,但是在手機(jī)端可以預(yù)覽,所有本項(xiàng)目把瀏覽器瀏覽格式改成手機(jī)端,支持Windows和Ubuntu. 本項(xiàng)目使用的是chromedriver來控制chrome來模擬人來操作來進(jìn)行文檔爬取2021-04-04

