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。

相关推荐
旖-旎3 小时前
《LeetCode 695 岛屿的最大面积 FloodFill DFS 解法》
c++·算法·力扣·深度优先遍历·floodfill
王老师青少年编程13 天前
信奥赛C++提高组csp-s之搜索进阶(搜索剪枝核心思想 )
c++·dfs·csp·信奥赛·搜索剪枝·搜索优化
浅念-17 天前
LeetCode 记忆化搜索 刷题总结
数据结构·算法·leetcode·职场和发展·深度优先·dfs
浅念-22 天前
LeetCode 回溯算法题——综合练习
数据结构·c++·算法·leetcode·职场和发展·深度优先·dfs
浅念-1 个月前
LeetCode回溯算法从入门到精通完整解析
开发语言·数据结构·c++·算法·leetcode·dfs·深度优先遍历
YL200404261 个月前
048路径总和III
数据结构·dfs
进击的荆棘1 个月前
递归、搜索与回溯——综合(下)
c++·算法·leetcode·深度优先·dfs
tiandyoin1 个月前
IPCONFIG重置网络
网络·ip·dfs·dns·vpn·cmd
图码1 个月前
矩阵边界遍历:顺时针与图案打印的两种高效解法
数据结构·python·线性代数·算法·青少年编程·矩阵·深度优先遍历
qq_296553271 个月前
矩阵对角线遍历:从暴力到最优的优雅解法
数据结构·线性代数·算法·青少年编程·矩阵·深度优先遍历