免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 2838 | 回复: 1
打印 上一主题 下一主题

请帮我看个word-ladder 的解法 [复制链接]

论坛徽章:
13
CU大牛徽章
日期:2013-03-14 14:14:082016科比退役纪念章
日期:2016-07-22 11:15:35数据库技术版块每日发帖之星
日期:2016-05-27 06:20:002015亚冠之吉达阿赫利
日期:2015-08-05 10:06:542015年亚洲杯之韩国
日期:2015-04-01 16:05:42双鱼座
日期:2014-11-13 11:04:24丑牛
日期:2014-07-25 17:29:54子鼠
日期:2014-04-25 12:25:45丑牛
日期:2014-04-17 08:35:48巨蟹座
日期:2014-04-16 16:50:05CU大牛徽章
日期:2013-03-14 14:14:29CU大牛徽章
日期:2013-03-14 14:14:26
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2016-04-03 16:10 |只看该作者 |倒序浏览
本帖最后由 hmchzb19 于 2016-04-03 16:12 编辑

我这里的代码都是参照这里的:http://interactivepython.org/run ... dLadderProblem.html
但是BFS 的代码我就不知道怎么搞了,因为BFS不返回,也没有stop,只有start.
  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())

复制代码
  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
复制代码
words.txt 是4个字母组成的单词共有3686个。
  1. wc -l words.txt
  2. 3685 words.txt
复制代码
BFS 什么都不返回。
BFS2 返回一个字典,但是BFS2返回的结果跟我预计的总是不对
  1. def bfs(g,start):
  2.     start.setDistance(0)
  3.     start.setPred(None)
  4.     vertQueue=[]
  5.     vertQueue.append(start)
  6.     while len(vertQueue) > 0:
  7.         currentVert=vertQueue.pop(0)
  8.         for nbr in currentVert.getConnections():
  9.             if (nbr.getColor()=='white'):
  10.                 nbr.setColor("gray")
  11.                 nbr.setDistance(currentVert.getDistance()+1)
  12.                 nbr.setPred(currentVert)
  13.                 vertQueue.append(nbr)
  14.         currentVert.setColor('black')


  15. def bfs2(g,start,stop):
  16.     parents={}
  17.     q=[]
  18.     q.append(start)
  19.     parents[start.id]=None

  20.     while len(q)> 0:
  21.         node=q.pop(0)
  22.         for neighbour in node.getConnections():
  23.             n=neighbour.id

  24.             if n not in parents:
  25.                 parents[n]=node.id
  26.                 if n==stop.id:
  27.                     return parents
  28.                 q.append(neighbour)

  29.     return parents
复制代码
  1.     g=buildGraph()
  2.     start=g.addVertex("fool")
  3.     stop=g.addVertex("sage")
  4.     path=bfs2(g,start,stop)
  5.     print(path)
复制代码
结果是
{'fool': None}

论坛徽章:
7
戌狗
日期:2013-12-15 20:43:38技术图书徽章
日期:2014-03-05 01:33:12技术图书徽章
日期:2014-03-15 20:31:17未羊
日期:2014-03-25 23:48:20丑牛
日期:2014-04-07 22:37:44巳蛇
日期:2014-04-11 21:58:0915-16赛季CBA联赛之青岛
日期:2016-03-17 20:36:13
2 [报告]
发表于 2016-04-05 22:25 |只看该作者
FOR print(path)
HERE:

  1. start = g.addVertex("fool")
  2. stop  = g.addVertex("sage")
复制代码
if fool, sage not in wordslist:
1: addEdge for fool, sage!
2: WHY? NO edge => NO connectedTo => getConnections == []
3: HOW? ADD fool, sage TO wordslist

if fool, sage in wordslist
1: you RESET connectedTo = {}
2: WHY?

  1. newVertice = Vertex(key)    # self.connectedTo = {}
  2. self.vertList[key] = newVertice
复制代码
3: SO getConnections == []
4: HOW? use:

  1. start = g.getVertex('fool')
  2. stop  = g.getVertex('sage')
复制代码
1 ge bfs2 de lizi:

dict = [ 'hot', 'dot', 'dog', 'lot', 'log', 'hit', 'cog' ]
star = 'hit'
stop = 'cog'

output:
  1. hit | hot | lot | log | cog
  2. hit | hot | dot | dog | cog
复制代码
  1. #!/usr/bin/perl
  2. use 5.018;

  3. my %Graph;

  4. sub buildGraph {
  5.     my $dic = shift;
  6.     my $end = length( $dic->[0] ) - 1;
  7.     for my $word (@$dic) {
  8.         for ( 0 .. $end ) {
  9.             my $pat = $word;
  10.             substr( $pat, $_, 1 ) = '.';
  11.             push @{ $Graph{$pat} }, $word;
  12.         }
  13.     }
  14. }

  15. sub getConnections {
  16.     my $node = shift;
  17.     map {
  18.         my $p = $node;
  19.         substr( $p, $_, 1 ) = '.';
  20.         @{ $Graph{$p} || [] }
  21.     } 0 .. length($node) - 1;
  22. }

  23. sub bfs2 {
  24.     my ( $star, $stop ) = @_;
  25.     my ( @todo, %has, %link ) = $star;

  26.     while (@todo) {
  27.         my %next;
  28.         $has{$_} ||= 1 for @todo;
  29.         for my $node (@todo) {
  30.             for my $neibeer ( getConnections $node ) {
  31.                 next if $has{$neibeer};
  32.                 $next{$neibeer} ||= 1;
  33.                 push @{ $link{$neibeer} }, $node;
  34.             }
  35.         }
  36.         @todo = keys %next;
  37.     }

  38.     sub {
  39.         my ( $word, $a ) = @_;
  40.         return join ' | ', $word, @$a if $word eq $star;
  41.         map { __SUB__->( $_, [ $word, @$a ] ) } @{ $link{$word} };
  42.     } ->( $stop, [] );
  43. }

  44. my $dict = [ 'hot', 'dot', 'dog', 'lot', 'log', 'hit', 'cog' ];
  45. my $star = 'hit';
  46. my $stop = 'cog';

  47. buildGraph $dict;
  48. my @path = bfs2 $star, $stop;
  49. say for @path;
复制代码
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP