You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

滑动拼图递归代码调试咨询:高时间复杂度下验证逻辑正确性

滑动谜题(Sliding Puzzle)解题记录与调试需求

我在2024年11月25日完成了LeetCode的《Sliding Puzzle》题目,最初用BFS解法实现,该解法时间复杂度为O(V+E),运行正常。之后尝试用递归(DFS)方式编写代码,但由于实现的时间复杂度达到O(V!)(量级接近720!),代码几乎无法运行。我需要找到能查看调试过程的网站或工具,来验证递归代码的逻辑是否符合预期。

递归DFS代码

from typing import List, Tuple
class Solution:
    def slidingPuzzle(self, board: List[List[int]]) -> int:
        def to_string(board: List[List[int]]) -> str:
            """Convert the 2x3 board into a string representation."""
            return "".join(str(num) for row in board for num in row)
        
        def swap(state: str, i: int, j: int) -> str:
            """Swap characters at index i and j in the string."""
            state = list(state)
            state[i], state[j] = state[j], state[i]
            return "".join(state)

        def dfs(state: str, depth: int) -> int:
            if state == target:
                return depth
            
            if state in memo:
                return float('inf')  # State already visited
            
            memo.add(state)
            zero_idx = state.index('0')
            min_moves = float('inf')

            for neighbor in directions[zero_idx]:
                new_state = swap(state, zero_idx, neighbor)
                moves = dfs(new_state, depth + 1)
                min_moves = min(min_moves, moves)
            
            memo.remove(state)  # Backtrack
            return min_moves
        
        # Target state
        target = "123450"
        
        # Convert the board to a string
        start = to_string(board)

        # Directions based on 2x3 board
        directions = [
            [1, 3],    # Index 0
            [0, 2, 4], # Index 1
            [1, 5],    # Index 2
            [0, 4],    # Index 3
            [1, 3, 5], # Index 4
            [2, 4]     # Index 5
        ]

        # Memoization to track visited states
        memo = set()

        # Perform DFS
        result = dfs(start, 0)
        return result if result != float('inf') else -1

BFS参考代码(时间复杂度O(V+E))

from typing import List
from collections import defaultdict, deque

class Solution:
    def slidingPuzzle(self, board: List[List[int]]) -> int:
        def swap(s: str, zero_idx: int, new_idx: int) -> str:
            char_arr = list(s)
            char_arr[zero_idx], char_arr[new_idx] = char_arr[new_idx], char_arr[zero_idx]
            return "".join(char_arr)

        target = "123450"
        start = "".join(str(board[r][c]) for r in range(len(board)) for c in range(len(board[0])))

        visited = set()
        directions = [
            [1, 3],    # Neighbors for index 0
            [0, 2, 4], # Neighbors for index 1
            [1, 5],    # Neighbors for index 2
            [0, 4],    # Neighbors for index 3
            [1, 3, 5], # Neighbors for index 4
            [2, 4]     # Neighbors for index 5
        ]

        queue = deque([start])
        visited.add(start)
        res = 0

        while queue:
            size = len(queue)
            for _ in range(size):
                curr = queue.popleft()
                if curr == target:
                    return res

                zero_idx = curr.index('0')  # Find the index of '0'

                for dir_idx in directions[zero_idx]:  # Valid moves for the zero's position
                    swapped = swap(curr, zero_idx, dir_idx)
                    if swapped in visited:
                        continue
                    visited.add(swapped)
                    queue.append(swapped)
            res += 1

        return -1

可用调试工具推荐

  • 本地IDE(PyCharm/VSCode):设置断点后单步执行,可实时查看递归调用栈、memo集合的变化、每一步的state和depth值,清晰追踪回溯过程。
  • LeetCode内置调试器:在题目提交页面使用调试功能,输入测试用例后单步运行,观察代码执行的每一步状态变化。
  • Python Tutor:可视化代码执行流程,能直观展示递归调用的层级、变量的修改过程,适合验证递归逻辑的正确性。

内容的提问来源于stack exchange,提问作者Emin-35

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.16 02:57:15