使用python实现字典转换问题

2020-01-02  本文已影响0人  dwq1666666
"""
题目内容:

给定两个单词(beginWord 和 endWord)和一个字典,找到从 beginWord 到 endWord 的最短转换序列的长度(如果没有满足条件的转换序列就什么都不输出)。转换需遵循如下规则:

每次转换只能改变一个字母;

转换过程中的中间单词必须是字典中的单词。
"""
import queue as que


def get_data():
    start = input()
    end = input()
    n = int(input())
    words = [input() for i in range(n)]

    return start, end, words

    # return {
    #     'start': 'hit',
    #     'end': 'cog',
    #     'word_list': ['hot', 'dot', 'dog', 'lot', 'log', 'cog'],
    # }


def get_next(current, next_param):

    cnt = 0
    for i in range(len(next_param)):
        if next_param[i] in current:
            cnt += 1

    if len(current) - cnt == 1:
        return True
    else:
        return False


def main():
    start, end, words = get_data()

    words.insert(0, start)
    list_len = len(words)
    looked = [0] * list_len
    looked[0] = 1

    q = que.Queue(list_len)

    q.put(start)
    min_setup = dict()
    min_setup[words[0]] = 1

    while q.empty() is False:
        current = q.get()

        for i in range(list_len):
            x = words[i]
            if looked[i] == 0 and get_next(current, x):
                q.put(x)
                looked[i] = 1
                min_setup[x] = min_setup[current] + 1  # 记录下最小步子
                # print('从{}走到了{},此时将{}的最短步数变为了{}'.format(current, x, min_setup[x], min_setup[current] + 1))

    # print(min_setup)
    if end in min_setup:
        return min_setup[end]
    else:
        return 'N'


if __name__ == '__main__':
    print(main())


上一篇 下一篇

猜你喜欢

热点阅读