Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1741395
  • 博文数量: 297
  • 博客积分: 285
  • 博客等级: 二等列兵
  • 技术积分: 3006
  • 用 户 组: 普通用户
  • 注册时间: 2010-03-06 22:04
个人简介

Linuxer, ex IBMer. GNU https://hmchzb19.github.io/

文章分类

全部博文(297)

文章存档

2020年(11)

2019年(15)

2018年(43)

2017年(79)

2016年(79)

2015年(58)

2014年(1)

2013年(8)

2012年(3)

分类: Python/Ruby

2016-04-06 21:45:10

代码多是参照这里的:首先是Graph 和Vertex 类

点击(此处)折叠或打开

  1. class Vertex:
  2.     def __init__(self,key,distance=0,pred=None,color="white"):
  3.         self.id=key
  4.         self.connectedTo={} #dict which contains all the other vertices it is connected to
  5.         self.pred=pred #for BFS tree/a list because we are dealing with cycles
  6.         self.color=color #for BFS tree
  7.         self.distance=distance

  8.     def addNeighbor(self,nbr,weight=0):
  9.         self.connectedTo[nbr]=weight

  10.     def __str__(self):
  11.         return str(self.id)+' connectedTo: '+str([x.id for x in self.connectedTo])
  12.         
  13.     def getConnections(self):
  14.         return self.connectedTo.keys()

  15.     def getId(self):
  16.         return self.id

  17.     def getWeight(self,nbr):
  18.         return self.connectedTo[nbr]
  19.     
  20.     def setPred(self,node):
  21.         self.pred=node

  22.     def getPred(self):
  23.         return self.pred
  24.     
  25.     def setDistance(self,distance):
  26.         self.distance=distance

  27.     def getDistance(self):
  28.         return self.distance
  29.     
  30.     def setColor(self,color):
  31.         self.color=color

  32.     def getColor(self):
  33.         return self.color


  34. #adjacency list implemented of the graph
  35. class Graph:
  36.     def __init__(self):
  37.         self.vertList={}
  38.         self.numVertices=0

  39.     def addVertex(self,key):
  40.         self.numVertices=self.numVertices+1
  41.         newVertice=Vertex(key)
  42.         self.vertList[key]=newVertice
  43.         return newVertice

  44.     def getVertex(self,n):
  45.         if n in self.vertList:
  46.             return self.vertList[n]
  47.         else:
  48.             return None

  49.     def __contains__(self,n):
  50.         return n in self.vertList

  51.     def addEdge(self,f,t,cost=0):
  52.         if f not in self.vertList:
  53.             nv=self.addVertex(f)
  54.         if t not in self.vertList:
  55.             nv=self.addVertex(t)
  56.         self.vertList[f].addNeighbor(self.vertList[t],cost)

  57.     def getVertices(self):
  58.         return self.vertList.keys()

  59.     def __iter__(self):
  60.         return iter(self.vertList.values())
下面是具体的实现。words.txt 是由4个字母组成的单词共有3686个,每行一个。

点击(此处)折叠或打开

  1. wc -l words.txt
  2. 3685 words.txt


点击(此处)折叠或打开

  1. #build thw word Ladder Graph
  2. def buildGraph(wordFile="words.txt"):
  3.     d={}
  4.     g=Graph()
  5.     wfile=open(wordFile,"r")
  6.     #create bucket of words that differ by one letter
  7.     for line in wfile:
  8.         word=line[:-1]
  9.         for i in range(len(word)):
  10.             bucket=word[:i]+'_'+word[i+1:]
  11.             if bucket in d:
  12.                 d[bucket].append(word)
  13.             else:
  14.                 d[bucket]=[word]

  15.     #add vertices and edges for words in the same bucket
  16.     for bucket in d.keys():
  17.         for word1 in d[bucket]:
  18.             for word2 in d[bucket]:
  19.                 if word1!=word2:
  20.                     g.addEdge(word1,word2)
  21.     return g

  22. def test_buildGraph():
  23.     g=buildGraph()
  24.     for v in g:
  25.         print(v)
  26.         #for w in v.getConnections():
  27.         # print(v.getId(),w.getId())

  28. #test_buildGraph()

  29. #BFS traverse Graph
  30. def bfs(g,start):
  31.     start.setDistance(0)
  32.     start.setPred(None)
  33.     vertQueue=[]
  34.     vertQueue.append(start)
  35.     while len(vertQueue) > 0:
  36.         currentVert=vertQueue.pop(0)
  37.         for nbr in currentVert.getConnections():
  38.             if (nbr.getColor()=='white'):
  39.                 nbr.setColor("gray")
  40.                 nbr.setDistance(currentVert.getDistance()+1)
  41.                 nbr.setPred(currentVert)
  42.                 vertQueue.append(nbr)
  43.         currentVert.setColor('black')


  44. def bfs2(g,start,stop):
  45.     parents={}
  46.     q=[]
  47.     q.append(start)
  48.     parents[start.id]=None

  49.     while len(q)> 0:
  50.         node=q.pop(0)
  51.         for neighbour in node.getConnections():
  52.             n=neighbour.id

  53.             if n not in parents:
  54.                 parents[n]=node.id
  55.                 if n==stop.id:
  56.                     return parents
  57.                 q.append(neighbour)
  58.     return parents


  59. def traverse(y):
  60.     #y: vertex
  61.     x=y
  62.     while(x.getPred()):
  63.         print(x.getId())
  64.         x=x.getPred()
  65.     print(x.getId())

  66. def test_traverse_with_bfs():
  67.     g=buildGraph()
  68.     start=g.getVertex("fool")
  69.     bfs(g,start)
  70.     traverse(g.getVertex("sage"))

  71. test_traverse_with_bfs()


  72. def getPath(start,finish,parents):
  73.     finish=finish.id
  74.     path=[finish]
  75.     if finish in parents:
  76.         node=parents[finish]
  77.         while(node!=start.id):
  78.             path.append(node)
  79.             node=parents[node]
  80.     else:
  81.         "No Path "
  82.     path.append(start.id)
  83.     return path[::-1]

  84. def test_traverse_withbfs2():
  85.     g=buildGraph()
  86.     start=g.getVertex("fool")
  87.     stop=g.getVertex("sage")
  88.     parents=bfs2(g,start,stop)
  89.     #print(parents.keys())
  90.     path=getPath(start,stop,parents)
  91.     print(path)

  92. test_traverse_withbfs2()
阅读(1454) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~