classneighbour(object):#邻居 def__init__(self,name,dist,point=()): self.name=name self.dist=dist self.predict=1e5 self.state=False#是否已遍历,相当于将数据分到close表或open表 self.beforcity="" self.point=point file1="./cityname.txt" file2="./dis_info.txt" f = open(file1, 'r') info=f.read() f.close() info txt_info=[] f = open(file2, 'r') line = f.readline() # 读取第一行 while line: #txt_data = eval(line) # 可将字符串变为元组 txt_info.append(line.replace("\n","")) # 列表增加 line = f.readline() # 读取下一 #print(txt_info) f.close()
cityList=[] for info in txt_info: info=info.split("=") cityList.append(city(info[0],eval(info[1])))
可视化地图
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
x_list=[] y_list=[] txt_list=[] for tmp in cityList: txt_list.append(tmp.name) x_list.append(tmp.coordination[0]) y_list.append(tmp.coordination[1])
#type(txt_list[1]) #可视化 import matplotlib.pyplot as plt plt.figure(dpi=300,figsize=(8,8)) plt.scatter(x_list, y_list) for i inrange(len(y_list)): plt.annotate(txt_list[i], xy = (x_list[i], y_list[i]), xytext = (x_list[i]+1, y_list[i]+1)) # 这里xy是需要标记的坐标,xytext是对应的标签坐标 plt.show()
导入城市之间的相连信息
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
file3="./citymap.txt" f = open(file3, 'r') info=f.read() f.close() #info #读取相邻节点 f = open(file3, 'r')#存相邻节点 line = f.readline() while line: tmp_list=line.replace("\n","").split(" ") tmpobject = [x for x in cityList if x.name == tmp_list[0]][0] for i inrange(1,len(tmp_list),2): tmpobject.nextcity.append(neighbour(tmp_list[i],eval(tmp_list[i+1]))) line = f.readline() # 读取下一行 f.close()
清除状态函数
1 2 3 4 5 6
defclearState(citylist): for city in citylist: tmp=city.nextcity for nei in tmp: nei.state=False clearState(cityList)
clearState(cityList) st = time.clock() record=[] disrecord=[] defdfs(begin,end):#寻找一个符合要求的路径 if begin==end: #print("!"*100) return currNeighbours = [x for x in cityList if x.name == begin][0].nextcity for curr in currNeighbours: if end in record: return if curr.state==True: continue else: curr.state=True if curr.name in record: continue #print("现在插入",curr.name) record.append(curr.name) disrecord.append(curr.dist) dfs(curr.name,end) if end in record: return record.pop(-1) disrecord.pop(-1) if currNeighbours[-1].state==True: record.pop(-1) disrecord.pop(-1) dfs(record[-1],end) record.append("Arad") disrecord.append(0) #dfs("Arad","Bucharest") dfs("Arad","Bucharest") cost = time.clock()-st print("路径",record) print(disrecord) print("路径总长度",sum(disrecord)) print("运行时间:",cost)
clearState(cityList) st = time.clock() defBFS(begin,end): finalRecord=[] finalDist=[] record=[] disrecord=[] record.append([begin]) disrecord.append([0]) whilelen(record)!=0: tmprecord=record.pop(0) tmpdis=disrecord.pop(0) if end in tmprecord: finalRecord.append(tmprecord[:]) finalDist.append(tmpdis[:]) continue currcity=tmprecord[-1]#当前扩展的节点 currNeighbours = [x for x in cityList if x.name == currcity][0].nextcity for nei in currNeighbours: if nei.name in tmprecord: continue tmprecord.append(nei.name) tmpdis.append(nei.dist) record.append(tmprecord[:]) disrecord.append(tmpdis[:]) tmprecord.pop(-1) tmpdis.pop(-1) # print(finalRecord) # print(finalDist) # print(len(finalRecord)) print("BFS所有可行路径:") sumdis=[] for i inrange(len(finalRecord)): print(finalRecord[i]) print("该路径长度:",sum(finalDist[i])) sumdis.append(sum(finalDist[i])) print('-'*100) minindex=sumdis.index(min(sumdis)) print("最短路径是:",finalRecord[minindex]) print("长度为:",sumdis[minindex]) BFS("Arad","Bucharest") cost = time.clock()-st print("运行时间:",cost)
st = time.clock() defDijkstra(begin,end): recordlist=[] #初始化recordlist for city in cityList: recordlist.append(neighbour(city.name,1e3)) curr = [x for x in recordlist if x.name == begin][0] curr.dist=0 # for rr in recordlist: # print(rr.name,rr.dist) #print(curr.name) for _ inrange(len(recordlist)): #寻找最短且未打标记的路径 mindis=1e3 mincity="" for city in recordlist: if city.state==False: if city.dist<mindis: mindis=city.dist mincity=city.name if mincity==end:#如果已经找到就直接退出#利用栈的结构,将结果输出 printlist=[] printlist.append(mincity) tmpfinal=[x for x in recordlist if x.name == mincity][0] finalmindis=tmpfinal.dist # while # print("最短路径",printlist) while tmpfinal.name!=begin: printlist.append(tmpfinal.beforcity) tmpfinal=[x for x in recordlist if x.name == tmpfinal.beforcity][0] #print("找到了!") printlist=list(reversed(printlist)) print(printlist) print("长度为:",finalmindis) break else: #print("当前扩展节点",mincity) curr = [x for x in recordlist if x.name == mincity][0] curr.state=True currNeighbours = [x for x in cityList if x.name == mincity][0].nextcity for tmpneighbour in currNeighbours: tmpnei= [x for x in recordlist if x.name == tmpneighbour.name][0] if tmpnei.state==Falseand curr.dist+ tmpneighbour.dist < tmpnei.dist: tmpnei.dist=curr.dist+ tmpneighbour.dist tmpnei.beforcity=mincity #print(tmpnei.name) # for rr in recordlist: # print(rr.name,rr.dist,rr.state) # print("-"*20) Dijkstra("Arad","Bucharest") cost = time.clock()-st print("运行时间:",cost)
st = time.clock() defastar(begin,end): recordlist=[] #初始化recordlist for city in cityList: recordlist.append(neighbour(city.name,1e4,city.coordination)) finalpoint=[x for x in recordlist if x.name == end][0].point#记录目标终点的坐标 curr = [x for x in recordlist if x.name == begin][0] curr.dist=0 curr.predict=getdis(curr.point,finalpoint) for _ inrange(len(recordlist)): #寻找最短且未打标记的路径 currmincity=None #先对队列进行排序 recordlist.sort(key=lambda x:x.predict) for city in recordlist: if city.state==False: currmincity=city break if currmincity.name==end:#如果已经找到就直接退出#利用栈的结构,将结果输出 printlist=[] printlist.append(currmincity.name) finalmindis=currmincity.dist tmpfinal=currmincity while tmpfinal.name!=begin: printlist.append(tmpfinal.beforcity) tmpfinal=[x for x in recordlist if x.name == tmpfinal.beforcity][0] #print("找到了!") printlist=list(reversed(printlist)) print(printlist) print("长度为:",finalmindis) break else: #print("当前扩展节点",mincity) curr = currmincity curr.state=True currNeighbours = [x for x in cityList if x.name == currmincity.name][0].nextcity for tmpneighbour in currNeighbours: tmpnei= [x for x in recordlist if x.name == tmpneighbour.name][0] newpredict=getdis(tmpnei.point,finalpoint) if tmpnei.state==Falseand curr.dist+ tmpneighbour.dist+ newpredict < tmpnei.predict: tmpnei.predict=curr.dist+ tmpneighbour.dist+ newpredict tmpnei.dist=curr.dist+ tmpneighbour.dist tmpnei.beforcity=currmincity.name astar("Arad","Bucharest") cost = time.clock()-st print("运行时间:",cost)