zgjja


私信TA

用户名:zgjja

访问量:10796

签 名:

X_X

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

  自我简介:

解题思路:
    同1878题。


注意事项:
    此题不能用二维数组表示状态(注释部分),会超时。

参考代码:

def bfs():
    global start, end, cache_state
    stack = [start]
    while stack:
        state = stack.pop(0)
        for direction in around:
            i, j = divmod(state.index('.'), 3)
            if 0 <= i + direction[0] < 3 and 0 <= j + direction[1] < 3:
                # temp = [list(state[3 * k:3 * k + 3]) for k in range(3)]
                # temp[i][j], temp[i + direction[0]][j + direction[1]] = temp[i + direction[0]][j + direction[1]], temp[i][j]
                # temp = ''.join(element for row in temp for element in row)
                temp = list(state)
                idx_0, idx_1 = 3 * i + j, 3 * (i + direction[0]) + j + direction[1]
                temp[idx_0], temp[idx_1] = temp[idx_1], temp[idx_0]
                temp = ''.join(temp)
                if temp not in cache_state:
                    cache_state.setdefault(temp, cache_state[state] + 1)
                    stack.append(temp)
                    if temp == end:
                        return cache_state[end]

                        
start, end = [input().strip() for _ in range(2)]
cache_state, around = {start: 0}, [[-1, 0], [0, -1], [1, 0], [0, 1]]
print(bfs())


 

0.0分

4 人评分

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

编程语言转换

万能编程问答

代码解释器

  评论区

牛比,我看湿了
2021-04-16 20:43:56
  • «
  • 1
  • »