最短路径只Dijkstra算法python实现
最短路径 Dijkstra算法
|
#coding: utf-8
#tulei.py
##一个图中有若干结点,他们的集合称为nodes;
##每个结点(node)有自己的名字,还有邻居,并有到各邻居的权值
import cPickle as p
class node:
def __init__(self,name):
self.name=name
self.father=None
self.neighbors={}
def __repr__(self):
return self.name
def join(self, cost, node_b):
self.neighbors[node_b.name]=cost
node_b.neighbors[self.name]=cost
class graph:
def __init__(self,name):
self.name=name
self.nodes={}
def who_is(self,name):
try:
return self.nodes[name]
except:
return None
def add(self,name_a,cost,name_b):
# 扩充图内容
if not self.who_is(name_a):
a=node(name_a)
self.nodes[name_a]=a
if not self.who_is(name_b):
b=node(name_b)
self.nodes[name_b]=b
self.nodes[name_a].join(cost,self.nodes[name_b])
def save(self):
# 写入文件
yes_or_no = raw_input('save or not(s/n): ')
if yes_or_no == 's':
f = file(self.name+'.data', 'w')
p.dump(self, f) # dump the object to a file
f.close()
def out(self):
# 从文件读出
try:
f = file(self.name+'.data')
return p.load(f)
except:
print self.name+'.data', "NOT found !"
def show(self):
# 显示图内容
print
print "this is ", self.name
print "---------------------------------------------------"
for i in self.nodes.values():
print i, i.neighbors
##g1=graph('g1')
##s1='a,15,b'
##while s1 != 'end':
## s2=s1.split(',')
## g1.add(s2[0],float(s2[1]),s2[2])
## s1=raw_input(':')
##g1.show()
##g1.save()
本文永久链接 http://www.tangblog.info/2009/09/12/Dijkstra_python.html
随机文章