Dijkstra's algorithm python

https://leetcode.com/problems/the-maze-ii/#/description

bfs solution with queue

class Solution(object):
    def shortestDistance(self, maze, start, destination):
        """
        :type maze: List[List[int]]
        :type start: List[int]
        :type destination: List[int]
        :rtype: bool
        """
        m = len(maze)
        n = len(maze[0])
        res = None

        def go(start, direction):
            # return the stop position and length
            i, j = start
            x, y = direction
            l = 0
            while 0 <= i + x < m and 0 <= j + y < n and maze[i + x][j + y] != 1:
                i += x
                j += y
                l += 1
            return l, (i, j)

        # bfs (dijkstra: https://en.wikipedia.org/wiki/Dijkstra's_algorithm)
        visited = {}
        q = [(0, tuple(start))]
        while q:
            length, cur = q.pop(0)
            if cur in visited and visited[cur] <= length:
                continue  # if cur is visited and with a shorter length, skip it.
            # visited all its neighbors
            for direction in [(-1, 0), (1, 0), (0, -1), (0, 1)]:
                l, np = go(cur, direction)
                q.append((length + l, np))  # push it into queue
            # mark it as visited
            visited[cur] = length
        if tuple(destination) not in visited:
            return -1
        else:
            return visited[tuple(destination)]

bfs solution with heap(PQ)

class Solution(object):
    def shortestDistance(self, maze, start, destination):
        """
        :type maze: List[List[int]]
        :type start: List[int]
        :type destination: List[int]
        :rtype: bool
        """
        m=len(maze)
        n=len(maze[0])
        res=None 
        def go(start, direction):
            # return the stop position and length
            i, j = start
            x, y= direction
            l=0
            while 0 <= i+x < m and 0 <= j+y < n and maze[i+x][j+y] != 1:
                i += x
                j += y
                l +=1
            return l, (i,j)
        # bfs (dijkstra: https://en.wikipedia.org/wiki/Dijkstra's_algorithm)
        visited={}
        q=[]
        heapq.heappush(q, (0, tuple(start)))
        while q: 
            length, cur = heapq.heappop(q)
            if cur in visited:
                continue # if 'cur' is visited skip it.
            # the length with 'cur' is the shotest path from start to 'cur'
            if cur == tuple(destination):
                return length
            # visited all its neighbors
            for direction in [(-1, 0), (1, 0), (0,-1), (0,1)]:
                l, np = go(cur, direction)
                heapq.heappush(q, (length+l, np)) # push it into queue
            # mark it as visited, 'length' is the shortest path from start to 'cur'
            visited[cur] = length  
        return -1  
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 12,774评论 0 33
  • afinalAfinal是一个android的ioc,orm框架 https://github.com/yangf...
    passiontim阅读 15,568评论 2 45
  • 前几天放假回家,和小清在路上散步,她的儿子在一旁玩儿,刚刚学会走路的小孩儿,走几步路也是跌跌撞撞的。 她看着儿子,...
    红面锦书阅读 1,050评论 0 1
  • 原文 侃问:“持志如心痛,一心在痛上,安有工夫说闲语、管闲事?”先生曰:“初学工夫如此用亦好,但要使知‘出入无时,...
    无住居士阅读 4,953评论 1 7
  • 夜灯依旧亮着路上已没有行人 音乐就这样响着你不知道唱的是什么 一切还是原来的模样蓝色的沙发摆满书的铁架一言不发的落...
    米芬阅读 341评论 0 3