边工作边刷题: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 ...
随机推荐
- fibonacci封闭公式
Description 2007年到来了.经过2006年一年的修炼,数学神童zouyu终于把0到100000000的Fibonacci数列 (f[0]=0,f[1]=1;f[i] = f[i-1]+f ...
- 【iOS】Quartz2D截屏
一.简单说明 在程序开发中,有时候需要截取屏幕上的某一块内容,比如捕鱼达人游戏.如图: 完成截屏功能的核心代码:- (void)renderInContext:(CGContextRef)ctx;调用 ...
- Dom4j 锁竞争性能低下解决
在最近的项目中使用 Dom4j 解析 xml 发现性能低下,有锁竞争的情况,解决如下: SAXParserFactory factory = new org.apache.xerces.jaxp.SA ...
- [WF] Quickstart Sample
[WF] Quickstart Sample 前言 Workflow Foundation(WF),总是给人一种很有用.可是却不知道怎么用的印象.这主要是因为前置的功课太多.要整合很多底层知识,才能完 ...
- Iscroll应用文档
Iscroll是一个非常不错的区域滑动插件. 不过它有个小小的不足,就是它的说明文档. 全英文不说,整理的也不咋好,官网上看着很乱,不容易查阅. 因此上网找了一些相关的文档说明并加以整理. Iscro ...
- 为什么要用visibility:hidden;代替display:none;?
为什么要用用visibility:hidden;代替display:none;?因为后者更加消耗浏览器: css绘制画面有两种形式:repaint 和reflow,当我们更改css属相如backgro ...
- mongodb driver c#语法
Definitions and BuildersThe driver has introduced a number of types related to the specification of ...
- 盒模型结构——3D盒模型
- 关于C#中泛型类型参数约束(where T : class)
.NET支持的类型参数约束有以下五种:where T : struct | T必须是一个结构类型where T : class ...
- JTS Geometry关系判断和分析
关系判断 Geometry之间的关系有如下几种: 相等(Equals): 几何形状拓扑上相等. 脱节(Disjoint): 几何形状没有共有的点. 相交(Intersects): 几何形状至少有一个共 ...