Word Ladder挑战中的图表不正确

时间:2017-11-13 17:00:34

标签: python-3.x graph undirected-graph

我正在尝试实现梯形图问题,我必须在最短的路径中将一个单词转换为另一个单词。显然我们可以使用广度优先搜索(BFS)来解决它但在此之前我们必须首先绘制图形。我已经实现了桶的概念,如果它们与桶类型相匹配,某些词落在桶中。但是我的图表没有正确实现。

给定的单词列表是[&#34; CAT&#34;,&#34; BAT&#34;,&#34; COT&#34;,&#34; COG&#34;,&#34; COW& #34;,&#34; RAT&#34;,&#34; BUT&#34;,&#34; CUT&#34;,&#34; DOG&#34;,&#34; WED&#34;] < / p>

因此,对于每个单词,我都可以创建一个存储桶。例如对于单词&#39; CAT&#39;,我可以有三个存储桶_AT,C_T,CA_。同样地,我可以为剩下的单词创建存储桶,并且与存储桶类型匹配的单词将属于这些存储桶。

用手实现应该给我一个这样的图形 enter image description here

由于图是无向的,所以对于顶点COG,其相邻顶点应该是DOG,COW,COT(关系工作两种方式)但是我得到COG连接到没有。这是我的代码下面

class Vertex:
    def __init__(self,key):
        self.id = key
        self.connectedTo = {}

    def addNeighbour(self,nbr,weight=0):
        self.connectedTo[nbr] = weight

    #string representation of the object
    def __str__(self):
        return str(self.id) + " is connected to " + str([x.id for x in self.connectedTo])

    def getConnections(self):
        return self.connectedTo.keys()

    def getId(self):
        return self.id

    def getWeight(self,nbr):
        return self.connectedTo[nbr]

class Graph:
    def __init__(self):
        self.vertList = {}
        self.numVertices = 0

    def addVertex(self,key):
        self.numVertices += 1
        newVertex = Vertex(key)
        self.vertList[key] = newVertex
        return newVertex

    def getVertex(self,n):
        if n in self.vertList:
            return self.vertList[n]
        else:
            return None

    def addEdge(self,f,t,cost=0):
        if f not in self.vertList:
            nv = self.addVertex(f)

        if t not in self.vertList:
            nv = self.addVertex(t)

        self.addVertex(f).addNeighbour(self.addVertex(t),cost)

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

    def __iter__(self):
        return iter(self.vertList.values())


wordList = ["CAT", "BAT", "COT", "COG", "COW", "RAT", "BUT", "CUT", "DOG", "WED"]

def buildGraph(wordList):
    d = {} #in this dictionary the buckets will be the keys and the words will be their values
    g = Graph()
    for i in wordList:
        for j in range(len(i)):
            bucket = i[:j] + "_" + i[j+1:]
            if bucket in d:
                #we are storing the words that fall under the same bucket in a list 
                d[bucket].append(i)
            else:
                d[bucket] = [i]

    # create vertices for the words under the buckets and join them
    #print("Dictionary",d)
    for bucket in d.keys():
        for word1 in d[bucket]:
            for word2 in d[bucket]:
                #we ensure same words are not treated as two different vertices
                if word1 != word2:
                    g.addEdge(word1,word2)

    return g

# get the graph object
gobj = buildGraph(wordList)

for v in gobj: #the graph contains a set of vertices
    print(v)

我得到的结果是

BUT is connected to ['BAT']
CUT is connected to ['COT']
COW is connected to ['COG']
COG is connected to []
CAT is connected to []
DOG is connected to ['COG']
RAT is connected to ['BAT']
COT is connected to []
BAT is connected to []

我希望结果像是

BUT is connected to ['BAT', 'CUT']
CUT is connected to ['CAT', 'COT', 'BUT']
and so on....

我做错了什么?

1 个答案:

答案 0 :(得分:1)

问题在于您的addEdge方法。

您正在检查图表中是否已存在顶点,确定。但如果它们存在,那么无论如何都要创建新的顶点并为这些新顶点添加边缘,丢掉之前的顶点。这就是为什么最后每个顶点只有一条边。

只需将addEdge的最后一行更改为:

self.vertList[f].addNeighbour(self.vertList[t],cost)