解题思路:
1.BFS遍历所有状态,储存状态及其对应的步数;
2.发现和结果吻合则退出。
注意事项:
1.使用字典存储某一状态和对应步数,便于查找重复状态,降低时间复杂度;
2.不要使用列表存储状态,因为列表不能作为字典键值,而应用字符串;
3.“跳杯”的过程可以用列表实现。
参考代码:
def bfs(): global start, end, cache_state, around stack = [start] while stack: temp_state = stack.pop(0) idx = temp_state.index('*') for i in around: if 0 <= idx + i < len(start) and temp_state[idx + i] != '*': temp = list(temp_state) temp[idx], temp[idx + i] = temp[idx + i], temp[idx] a = "".join(temp) if a not in cache_state: cache_state.setdefault(a, cache_state[temp_state] + 1) stack.append(a) if a == end: return cache_state[a] start, end = [input() for _ in range(2)] cache_state = {start: 0} around = [-3, -2, -1, 1, 2, 3] print(bfs())
0.0分
4 人评分
import os import sys from collections import deque import copy start = input() target = input() result = 0 def bfs(): global result q = deque([[start,0]]) while q: A,n = q.popleft() if A == target: print(n) break empty = A.index("*") for i in [-3,-2,-1,1,2]: x = i+empty if 0<=x<len(start): B = list(A) a = B[x] B[x] = "*" B[empty] = a q.append(["".join(B),n+1]) bfs() 请问我这个代码为什么会内存超限
C语言程序设计教程(第三版)课后习题10.2 (C语言代码)浏览:1456 |
罗列完美数 (C语言代码)浏览:491 |
C语言程序设计教程(第三版)课后习题1.6 (C语言代码)浏览:662 |
杨辉三角 (C语言代码)浏览:676 |
C语言程序设计教程(第三版)课后习题8.7 (C语言代码)浏览:795 |
C语言程序设计教程(第三版)课后习题1.5 (C语言代码)浏览:518 |
2004年秋浙江省计算机等级考试二级C 编程题(1) (C语言代码)浏览:580 |
C二级辅导-阶乘数列 (C语言代码)浏览:391 |
校门外的树 (C语言代码)浏览:524 |
WU-数字整除 (C++代码)浏览:1578 |