边工作边刷题:70天一遍leetcode: day 85-4
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 deque
import sys
class 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<m and 0<=y0<n and not visited[x0][y0]:
visited[x0][y0]=True # error 3: dont forget
if grid[x0][y0]==0:
self.dist[x0][y0]+=d
self.reach[x0][y0]+=1
q.append((x0,y0))
if grid[x0][y0]==1:
count+=1
return count==total
m,n=len(grid),len(grid[0])
total = sum([val for line in grid for val in line if val==1])
self.dist = [[0 for y in xrange(n)] for x in xrange(m)]
self.reach = [[0 for y in xrange(n)] for x in xrange(m)]
for x in xrange(m):
for y in xrange(n):
if grid[x][y]==1:
if not bfs(grid, m, n, x, y, total):
return -1
shortest = sys.maxint
for x in xrange(m):
for y in xrange(n):
if self.reach[x][y]==total:
shortest = min(self.dist[x][y], shortest)
return shortest
sol = Solution()
assert sol.shortestDistance([[1,0,2,0,1],[0,0,0,0,0],[0,0,1,0,0]])==7, "must be 7"
assert sol.shortestDistance([[1]])==-1, "must be -1"
边工作边刷题:70天一遍leetcode: day 85-4的更多相关文章
- 边工作边刷题:70天一遍leetcode: day 85
Find the Celebrity 要点: 这题从solution反过来想比较好:loop through n同时maintain一个candidate:如果cand认识某个i,那么modify c ...
- 边工作边刷题:70天一遍leetcode: day 89
Word Break I/II 现在看都是小case题了,一遍过了.注意这题不是np complete,dp解的time complexity可以是O(n^2) or O(nm) (取决于inner ...
- 边工作边刷题:70天一遍leetcode: day 77
Paint House I/II 要点:这题要区分房子编号i和颜色编号k:目标是某个颜色,所以min的list是上一个房子编号中所有其他颜色+当前颜色的cost https://repl.it/Chw ...
- 边工作边刷题:70天一遍leetcode: day 78
Graph Valid Tree 要点:本身题不难,关键是这题涉及几道关联题目,要清楚之间的差别和关联才能解类似题:isTree就比isCycle多了检查连通性,所以这一系列题从结构上分以下三部分 g ...
- 边工作边刷题:70天一遍leetcode: day 85-3
Zigzag Iterator 要点: 实际不是zigzag而是纵向访问 这题可以扩展到k个list,也可以扩展到只给iterator而不给list.结构上没什么区别,iterator的hasNext ...
- 边工作边刷题:70天一遍leetcode: day 101
dp/recursion的方式和是不是game无关,和game本身的规则有关:flip game不累加值,只需要一个boolean就可以.coin in a line II是从一个方向上选取,所以1d ...
- 边工作边刷题:70天一遍leetcode: day 1
(今日完成:Two Sum, Add Two Numbers, Longest Substring Without Repeating Characters, Median of Two Sorted ...
- 边工作边刷题:70天一遍leetcode: day 70
Design Phone Directory 要点:坑爹的一题,扩展的话类似LRU,但是本题的accept解直接一个set搞定 https://repl.it/Cu0j # Design a Phon ...
- 边工作边刷题:70天一遍leetcode: day 71-3
Two Sum I/II/III 要点:都是简单题,III就要注意如果value-num==num的情况,所以要count,并且count>1 https://repl.it/CrZG 错误点: ...
- 边工作边刷题:70天一遍leetcode: day 71-2
One Edit Distance 要点:有两种解法要考虑:已知长度和未知长度(比如只给个iterator) 已知长度:最好不要用if/else在最外面分情况,而是loop在外,用err记录misma ...
随机推荐
- Hibernate Validator
http://docs.jboss.org/hibernate/validator/4.2/reference/zh-CN/html_single/#example-group-interfaces
- [moka同学摘录]iptables防火墙规则的添加、删除、修改、保存
文章来源:http://www.splaybow.com/post/iptables-rule-add-delete-modify-save.html 本文介绍iptables这个Linux下最强大的 ...
- 利用jquery实现网页禁止鼠标右键、禁止复制
很多时候,网站的内容辛苦写法被轻松复制,为了不让自己的劳动成果外流,可以利用禁止鼠标右键等方式保护自己的原创内容! 方式1:禁止鼠标右键操作 <script src="http://l ...
- Android5.0新特性——图片和颜色(drawable)
图片和颜色 tint属性 tint属性一个颜色值,可以对图片做颜色渲染,我们可以给view的背景设置tint色值,给ImageView的图片设置tint色值,也可以给任意Drawable或者NineP ...
- winform(进程和线程)
一.进程:需要有用Process类用法一:Process.Start("calc");(不好用)该方法弊端:有许多程序不知道它的运行名字到底是什么,如果写错了,就会出现程序崩溃错误 ...
- nodeJS中npm常见的命令
常用的nodeJS中npm的命令:npm主要是node包管理和发布的工具.npm常用的命令:1:npm install <name> //(下载包) 下载后的包放在当前路径下面 npm i ...
- 如何在树莓派上运行雷神之锤III
昨天在树莓派上尝试运行了一下雷神之锤III,流畅运行,效果不错~~~ RPI这个小身板的东东总是可以给你带来惊喜,这里记录一下步骤以备后续再用 先确保RPI的程序和固件都已经更新 sudo apt-g ...
- 2014年听写VOA50篇
在沪江英语的VOA听写栏目上听写完成50篇,听写笔记PDF. 103.VOASP.2014奥巴马国情咨文(1-3).mp3 104.VOASP.2014奥巴马国情咨文(2-3).mp3 105.VOA ...
- [leetcode] Number of Islands
Number of Islands Given a 2d grid map of '1's (land) and '0's (water), count the number of islands. ...
- Hibernate的各种关联关系
1.有多中映射 方法 //用XML配置时 <mapping resource="com/liugch/bean/Student.hbm.xml" /> //用注解配置时 ...