Python教程

用python写的推箱子搜索程序

本文主要是介绍用python写的推箱子搜索程序,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
 1 # -*- coding: gbk -*-
 2 from functools import reduce
 3 from copy import deepcopy
 4 import re
 5 def s(l): return reduce(lambda x,y:x+y, l, '')
 6 class Brd:
 7     def __init__(m, s):
 8         m.x = m.y = -1; m.b = []
 9         b = [x for x in re.split('[\r|\n]', s.upper()) if x != '']
10         for y in range(len(b)):
11             x = b[y].find('?')
12             if x != -1: (m.x, m.y) = (x, y)
13             m.b.append(list(b[y]))
14     def __str__(m): return reduce(lambda x,y:s(x)+'\n'+s(y), m.b, '')
15     def equal(m, bstr):
16         m.b[m.y][m.x] = '.'; eq = str(m) == bstr; m.b[m.y][m.x] = '?'
17         return eq
18 start = Brd('''
19   WWWWWW
20   W....W
21 WWWBBB.W
22 W?.B...W
23 W.B...WW
24 WWWW..W 
25    WWWW 
26 ''')
27 start = Brd('''
28   WWWWWW
29   W....W
30 WWW..B.W
31 W..B...W
32 W?.BBBWW
33 WWWW..W 
34    WWWW 
35 ''')
36 target = str(Brd('''
37   WWWWWW
38   W....W
39 WWW....W
40 W...BB.W
41 W..BBBWW
42 WWWW..W 
43    WWWW 
44 '''))
45 tried = {}
46 def step(b, dx, dy):
47     if b.b[b.y+dy][b.x+dx] == 'W': return None
48     b = deepcopy(b); c = b.b; x = b.x; y = b.y
49     if c[y+dy][x+dx] == '.':
50         (c[y+dy][x+dx], c[y][x]) = ('?', '.')
51         (b.x, b.y) = (x+dx, y+dy)
52         return b
53     x2=dx*2; y2=dy*2 # 2*(dx,dy) = (dx,dy,dx,dy)
54     if c[y+y2][x+x2] == '.':
55         (c[y+y2][x+x2], c[y+dy][x+dx], c[y][x]) = ('B', '?', '.')
56         (b.x, b.y) = (x+dx, y+dy)
57         return b
58     return None
59 def search(brd, path):
60     if brd.equal(target):
61         for p in path: print(p)
62         return True
63     s = str(brd)
64     if tried.get(s, False): return False
65     tried[s] = True
66     for (dx, dy) in [[-1,0],[1,0],[0,-1],[0,1]]:
67         t = step(brd, dx, dy)
68         if t == None: continue
69         if search(t, path+[t]): return True
70     return False
71 search(start, [start])

能用但贼慢。

 

这篇关于用python写的推箱子搜索程序的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!