1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
| from collections import deque
mp = [1, 2, 3, 4, 6, 7, 8, 9, 11, 12, 13, 14] vis = [False] * 13 a = [0] * 5
def bfs(): global a cnt = [0] * 5 q = deque() q.append(a[0]) cnt[0] = 1 while q: x = q.popleft() for i, y in enumerate(a): if abs(x - y) in [1, 5] and cnt[i] == 0: q.append(y) cnt[i] = 1 if sum(cnt) == 5: return True else: return False
def dfs(s): global ans, vis if s == 6: if bfs(): ans += 1 else: for i in range(12): if not vis[i]: vis[i] = True a[s - 1] = mp[i] dfs(s + 1) vis[i] = False
ans = 0
dfs(1) print(ans // 120)
|