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。

相关推荐
Tisfy8 小时前
LeetCode 1722.执行交换操作后的最小汉明距离:连通图
算法·leetcode·dfs·题解·深度优先搜索·连通图
承渊政道1 天前
【递归、搜索与回溯算法】(floodfill算法:从不会做矩阵题,到真正掌握搜索扩散思想)
数据结构·c++·算法·leetcode·矩阵·dfs·bfs
进击的荆棘2 天前
递归、搜索与回溯——二叉树中的深搜
数据结构·c++·算法·leetcode·深度优先·dfs
进击的荆棘2 天前
递归、搜索与回溯——回溯
数据结构·c++·算法·leetcode·dfs
naijil5 天前
Atcoder - abc453_d Go Straight
dfs·搜索
承渊政道7 天前
【递归、搜索与回溯算法】(递归问题拆解与经典模型实战大秘笈)
数据结构·c++·学习·算法·macos·dfs·bfs
独断万古他化25 天前
【算法通关】二叉树中的深搜:DFS 递归解题套路
算法·二叉树·深度优先·dfs·递归
不染尘.1 个月前
拓扑排序算法
开发语言·数据结构·c++·算法·排序算法·广度优先·深度优先遍历
落地加湿器1 个月前
Acwing算法课图论与搜索笔记
c++·笔记·算法·图论·dfs·bfs·图搜索算法
无尽的罚坐人生1 个月前
hot 100 200. 岛屿数量
算法·dfs