Leetcode 2850. Minimum Moves to Spread Stones Over Grid

  • Leetcode 2850. Minimum Moves to Spread Stones Over Grid
    • 1. 算法思路
    • 2. 代码实现
  • 题目链接:2850. Minimum Moves to Spread Stones Over Grid

1. 算法思路

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

2. 代码实现

给出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。

你可能感兴趣的:(leetcode笔记,leetcode,2850,深度优先遍历,dfs,周赛362)