阿小信大人的头像
Talk is cheap. Show me the code. Linus Torvalds

迷宫题2014-09-02 05:21

题目:从左边入口处的 2011 进去,在迷宫里转悠,最后变成 2012 从右边出来。 你可以在迷宫里转圈,可以重复之前走过的路,但不能往回退着走。

#! /usr/bin/env python
# -*- coding:utf-8 -*-
# 作者:@ccmouse82

paths = [
("+7", lambda x : True, lambda x : x + 7),
("/2", lambda x : x % 2 == 0, lambda x : x / 2),
("*3", lambda x : True, lambda x : x * 3),
("-5", lambda x : True, lambda x : x - 5),
]

nodes = [
[(1, paths[0]), (1, paths[1])],
[(0, paths[0]), (0, paths[1]), (2, paths[2]), (2, paths[3])],
[(1, paths[2]), (1, paths[3])],
]

src_s, src_v = (0, 2011)

dest_s, dest_v = (2, 2012)

states = {(src_s, src_v, None) : (None, None, None)}

Q = [(src_s, src_v, None)]

while Q:
    s, v, path = Q.pop(0)
    if (s, v) == (dest_s, dest_v):
        dest_path = path
        break
    for (next_s, next_path) in nodes[s]:
        if next_path != path:
            desc, checker, trans = next_path
            if checker(v):
                next_v = trans(v)
                if not states.has_key((next_s, next_v, next_path)):
                    states[(next_s, next_v, next_path)] = (s, v, path)
                    Q.append((next_s, next_v, next_path))

def print_path(s, v, path, states):
    prev_s, prev_v, prev_path = states[(s, v, path)]
    if prev_s != None and prev_v != None:
        print_path(prev_s, prev_v, prev_path, states)
        print path[0],

print src_v,
print_path(dest_s, dest_v, dest_path, states)
print "=", dest_v

如果您觉得从我的分享中得到了帮助,并且希望我的博客持续发展下去,请点击支付宝捐赠,谢谢!

若非特别声明,文章均为阿小信的个人笔记,转载请注明出处。文章如有侵权内容,请联系我,我会及时删除。

#Python#   阅读[3155] 评论[0]

你可能也感兴趣的文章推荐

本文最近访客

网友185.*.*.1[火星]2022-09-25 06:52
网友185.*.*.14[火星]2022-09-25 06:46
网友185.*.*.26[火星]2022-09-25 06:36
网友185.*.*.13[火星]2022-09-25 06:35

发表评论