773.滑动谜题
发布日期:2021-05-06 11:08:31 浏览次数:15 分类:精选文章

本文共 1281 字,大约阅读时间需要 4 分钟。

在这里插入图片描述

在这里插入图片描述

class Solution:    def slidingPuzzle(self, board):        res = []        board_res = [[1, 2, 3], [4, 5, 0]]        ans = 0        if board == board_res:            return ans        q = [board]        new = [[-1, 0], [0, 1], [1, 0], [0, -1]]        while q:            size = len(q)            ans = ans + 1            while size:                # 查找0的坐标                for i in range(2):                    for j in range(3):                        if q[0][i][j] == 0:                            zero_i = i                            zero_j = j                            break                for new_x, new_y in new:                    tmp = copy.deepcopy((q[0]))                    if 0 <= zero_i + new_x <= 1 and 0 <= zero_j + new_y <= 2:                        # 交换位置                        tmp[zero_i][zero_j], tmp[zero_i + new_x][zero_j + new_y] = tmp[zero_i + new_x][zero_j + new_y], \                                                                                tmp[zero_i][zero_j]                        if tmp not in res:                            res.append(tmp)                            if tmp == board_res:                                return ans                            q.append(tmp)                size = size - 1                q.pop(0)        return -1
上一篇:775. 全局倒置与局部倒置
下一篇:SQL(二)

发表评论

最新留言

感谢大佬
[***.8.128.20]2025年03月28日 20时36分23秒