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。

相关推荐
无尽的罚坐人生14 小时前
hot 100 200. 岛屿数量
算法·dfs
像污秽一样15 小时前
算法设计与分析-习题9.2
数据结构·算法·排序算法·dfs
像污秽一样16 小时前
算法设计与分析-习题9.1
数据结构·算法·dfs·dp·贪婪
像污秽一样1 天前
算法设计与分析-习题8.2
数据结构·算法·排序算法·dfs·化简
像污秽一样2 天前
算法设计与分析-习题8.1
数据结构·算法·dfs·dp
I_LPL2 天前
hot100 图论专题
算法·图论·dfs·bfs·拓扑排序
XiaoYu1__2 天前
算法笔记·其一:从递归到回溯——以全排列与N皇后问题为例
c++·笔记·算法·深度优先遍历
We་ct2 天前
LeetCode 427. 建立四叉树:递归思想的经典应用
前端·算法·leetcode·typescript·dfs·深度优先遍历·分治
样例过了就是过了2 天前
LeetCode热题100 N 皇后
数据结构·c++·算法·leetcode·dfs·深度优先遍历
样例过了就是过了2 天前
LeetCode热题100 分割回文串
数据结构·c++·算法·leetcode·深度优先·dfs