2577. 在网格图中访问一个格子的最少时间

如果移动第一步, 那么剩下的格子都可以通过左右横跳来到达;

实质上是求最短距离, 注意的就是因为每次只能移动一步, 所以相邻的格子的数值的奇偶性是相反的,

写了一个dijkstra

class Solution:
    def minimumTime(self, grid: List[List[int]]) -> int:
        if grid[0][1] > 1 and grid[1][0] > 1:
            return -1
        max_row = len(grid) - 1
        max_col = len(grid[0]) - 1
        # 此处需要计算最小路径, 可以使用a* 或者dijkstra或者广度优先
        # 先用dijkstra来进行计算
        stable_set = set()
        value_queue = []
        heapq.heappush(value_queue, (0, (0, 0)))

        def handler_next_pos(m ,n, value):
            if (m, n) not in stable_set:
                v = grid[m][n]
                v = max(value + 1, v)
                if (v - value) % 2 == 0:
                    v += 1
                heapq.heappush(value_queue, (v, (m, n)))

        while heapq:
            value, pos = heapq.heappop(value_queue)
            if pos in stable_set:
                continue
            if pos == (max_row, max_col):
                return value

            i, j = pos
            if i > 0:
                m, n = i-1, j
                handler_next_pos(m, n, value)
            if j > 0:
                m, n = i, j - 1
                handler_next_pos(m, n, value)
            if i < max_row:
                m, n = i+1, j
                handler_next_pos(m, n, value)
            if j < max_col:
                m, n = i, j + 1
                handler_next_pos(m, n, value)
            stable_set.add(pos)
        raise Exception

稍微改改就是 A* 了

class Solution:
    def minimumTime(self, grid: List[List[int]]) -> int:
        if grid[0][1] > 1 and grid[1][0] > 1:
            return -1
        max_row = len(grid) - 1
        max_col = len(grid[0]) - 1
        # 此处需要计算最小路径, 可以使用a* 或者dijkstra或者广度优先
        # 先用a *来进行计算
        stable_set = set()
        value_queue = []
        # 期望距离, 真实距离, 坐标
        heapq.heappush(value_queue, (max_row + max_col, 0, (0, 0)))
        def handler_next_pos(m ,n, value):
            if (m, n) not in stable_set:
                v = grid[m][n]
                v = max(value + 1, v)
                if (v - value) % 2 == 0:
                    v += 1
                e_v = v + max_col + max_row - m - n
                heapq.heappush(value_queue, (e_v, v, (m, n)))
        while heapq:
            _, value, pos = heapq.heappop(value_queue)
            if pos in stable_set:
                continue
            if pos == (max_row, max_col):
                return value

            i, j = pos
            if i > 0:
                m, n = i-1, j
                handler_next_pos(m, n, value)
            if j > 0:
                m, n = i, j - 1
                handler_next_pos(m, n, value)
            if i < max_row:
                m, n = i+1, j
                handler_next_pos(m, n, value)
            if j < max_col:
                m, n = i, j + 1
                handler_next_pos(m, n, value)
            stable_set.add(pos)
        raise Exception
posted @   茫茫碧落  阅读(20)  评论(0编辑  收藏  举报
点击右上角即可分享
微信分享提示