博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
边工作边刷题:70天一遍leetcode: day 85-4
阅读量:4973 次
发布时间:2019-06-12

本文共 1812 字,大约阅读时间需要 6 分钟。

Walls and Gates

要点:

  • 同样是bfs,这题可以用渲染的方法(即全部gate进初始q),注意区别Shortest Distance from All Buildings。那道题要找到某个点到"all" buildings的距离,所以不能用渲染,因为不是到该点的一条路径。而本题类似surrounded region,最终的最佳路径只取一条路径
  • bfs的方法全是在展开后入q前更新
  • 剪枝:只要值更新了,就一定是最小值。不用入q了

错误点:

  • 忘了更新距离。因为gate是0,所以距离可以统一更新为从哪来的+1

# You want to build a house on an empty land which reaches all buildings in the shortest amount of distance. You can only move up, down, left and right. You are given a 2D grid of values 0, 1 or 2, where:# Each 0 marks an empty land which you can pass by freely.# Each 1 marks a building which you cannot pass through.# Each 2 marks an obstacle which you cannot pass through.# For example, given three buildings at (0,0), (0,4), (2,2), and an obstacle at (0,2):# 1 - 0 - 2 - 0 - 1# |   |   |   |   |# 0 - 0 - 0 - 0 - 0# |   |   |   |   |# 0 - 0 - 1 - 0 - 0# The point (1,2) is an ideal empty land to build a house, as the total travel distance of 3+3+1=7 is minimal. So return 7.# Note:# There will be at least one building. If it is not possible to build such house according to the above rules, return -1.from collections import dequeimport sysclass Solution(object):    def shortestDistance(self, grid):        """        :type grid: List[List[int]]        :rtype: int        """        def bfs(grid, m, n, x, y, total):            visited = [[False]*n for _ in xrange(m)] # error: don't use x,y            q = deque([(x,y)]) # error 1            count=0            dirs = [(1,0),(0,1),(-1,0),(0,-1)]            d = 0            while q:                ql = len(q) # error 2: use single object                d+=1                for _ in xrange(ql):                    x,y = q.popleft()                    for xd,yd in dirs:                        x0,y0 = x+xd,y+yd                        if 0<=x0

转载于:https://www.cnblogs.com/absolute/p/5815776.html

你可能感兴趣的文章
centos iptables
查看>>
unity3d 移动与旋转 2
查看>>
寻找二叉查找树中比指定值小的所有节点中最大的那个节点
查看>>
如何设置输入框达到只读效果
查看>>
RT3070 USB WIFI 在连接socket编程过程中问题总结
查看>>
MIS外汇平台荣获“2013年全球最佳STP外汇交易商”
查看>>
LeetCode 题解之Add Digits
查看>>
hdu1502 , Regular Words, dp,高精度加法
查看>>
20120227_CET6
查看>>
SpringBoot在idea中的热部署配置
查看>>
MyEclipse连接SQL Server 2008数据库的操作方法
查看>>
leetcode【67】-Bulb Switcher
查看>>
JS验证图片格式和大小并预览
查看>>
laravel5.2 移植到新服务器上除了“/”路由 ,其它路由对应的页面显示报404错误(Object not found!)———新装的LAMP没有加载Rewrite模块...
查看>>
编写高质量代码--改善python程序的建议(六)
查看>>
windows xp 中的administrator帐户不在用户登录内怎么解决?
查看>>
接口和抽象类有什么区别
查看>>
Codeforces Round #206 (Div. 2)
查看>>
**p
查看>>
优先队列详解
查看>>