Leetcode 2850. Minimum Moves to Spread Stones Over Grid

  • [Leetcode 2850. Minimum Moves to Spread Stones Over Grid](#Leetcode 2850. Minimum Moves to Spread Stones Over Grid)
    • [1. 算法思路](#1. 算法思路)
    • [2. 代码实现](#2. 代码实现)

1. 算法思路

这一题由于棋盘比较小,只是一个3x3的棋盘,所有的移动策略总量有限,因此,这里我们直接的一个思路就是使用一个深度优先遍历来考察所有可能的移动策略,然后从中取出move总数最小的一种方案对应的结果。

2. 代码实现

给出python代码实现如下:

python 复制代码
class Solution:
    def minimumMoves(self, grid: List[List[int]]) -> int:
        _from = [0 for _ in range(9)]
        _to = [0 for _ in range(9)]
        for i in range(3):
            for j in range(3):
                idx = i * 3 + j
                if grid[i][j] == 0:
                    _to[idx] = 1
                elif grid[i][j] > 1:
                    _from[idx] = grid[i][j] - 1
                    
        def cal_distance(i, j):
            r1, c1 = i//3, i%3
            r2, c2 = j//3, j%3
            return abs(r1-r2) + abs(c1-c2)
                    
        def dfs(idx):
            if idx >= 9:
                return 0
            if _from[idx] == 0:
                return dfs(idx+1)
            res = math.inf
            _from[idx] -= 1
            for i in range(9):
                if _to[i] == 0:
                    continue
                _to[i] = 0
                res = min(res, cal_distance(idx, i) + dfs(idx))
                _to[i] = 1
            _from[idx] += 1
            return res
        
        return dfs(0)

提交代码评测得到:1171ms,占用内存16.4MB。

相关推荐
hnjzsyjyj1 小时前
洛谷 B3622:枚举子集(递归实现指数型枚举)← DFS
数据结构·dfs
hnjzsyjyj2 天前
全排列问题DFS实现执行示意图
数据结构·dfs
XLYcmy2 天前
2026游戏安全技术竞赛-PC客户端安全-初赛 求解起点到终点的最短路径
windows·python·网络安全·dfs·bfs·游戏安全·曼哈顿距离
Tisfy7 天前
LeetCode 1722.执行交换操作后的最小汉明距离:连通图
算法·leetcode·dfs·题解·深度优先搜索·连通图
承渊政道8 天前
【递归、搜索与回溯算法】(floodfill算法:从不会做矩阵题,到真正掌握搜索扩散思想)
数据结构·c++·算法·leetcode·矩阵·dfs·bfs
进击的荆棘9 天前
递归、搜索与回溯——二叉树中的深搜
数据结构·c++·算法·leetcode·深度优先·dfs
进击的荆棘9 天前
递归、搜索与回溯——回溯
数据结构·c++·算法·leetcode·dfs
naijil12 天前
Atcoder - abc453_d Go Straight
dfs·搜索
承渊政道14 天前
【递归、搜索与回溯算法】(递归问题拆解与经典模型实战大秘笈)
数据结构·c++·学习·算法·macos·dfs·bfs
独断万古他化1 个月前
【算法通关】二叉树中的深搜:DFS 递归解题套路
算法·二叉树·深度优先·dfs·递归