欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Python 数据结构与算法分析 七、图算法之广度优先搜索

程序员文章站 2022-05-23 11:08:21
...

词梯图的构建

from pythonds.graphs import Graph
def buildGraph(wordFile):
    d = {}
    g = Graph()

    wfile = open(wordFile, 'r')
    # 创建词桶
    for line in wfile:
        word = line[:-1]
        for i in range(len(word)):
            bucket = word[:i] + '_' + word[i+1:]
            if bucket in d:
                d[bucket].append(word)
            else:
                d[bucket] = [word]
    # 为同一个通风中的单词添加顶点和边
    for bucket in d.keys():
        for word1 in d[bucket]:
            for word2 in d[bucket]:
                if word1 != word2:
                    g.addEdge(word1, word2)
    return g

广度优先搜索的实现