zgjja


私信TA

用户名:zgjja

访问量:10817

签 名:

X_X

等  级
排  名 147
经  验 7111
参赛次数 0
文章发表 71
年  龄 0
在职情况 学生
学  校
专  业 X_X

  自我简介:

解题思路:
    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 人评分

看不懂代码?想转换其他语言的代码? 或者想问其他问题? 试试问问AI编程助手,随时响应你的问题:

编程语言转换万能编程问答  

代码解释器

代码纠错

SQL生成与解释

  评论区

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()
请问我这个代码为什么会内存超限
2023-04-07 11:44:11
  • «
  • 1
  • »