边工作边刷题: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 ...
随机推荐
- mysql zip install
1.Question Description: 1.1 version: mysql-5.7.11-64 1.2 form: zip file 1.3 >mysqld --install (su ...
- Hibernate中的一对一关联和组件的映射
Hibernate提供了两种映射一对一映射关联关系的方式: 01.按照外键映射 02.按照主键映射 下面以员工账号表和员工档案表(员工账号和档案表之间是一对一的关系)为例,介绍这两种映射关系,并使用这 ...
- Follow me to learn what is repository pattern
Introduction Creating a generic repository pattern in an mvc application with entity framework is th ...
- Webform(Repeater控件)
一.Repeater控件 有五大模板 ItemTemplate :有多少条数据,执行多少遍 AlternatingItemTemplate : 对交替数据项进行格式设置 Se ...
- [程序人生]前途无"亮‘’的大学
转眼之间就到大四了,今天晚上很迷茫,很纠结,想了好多,好多,真的,长大之后,自从第一次失恋之后,第一次会想到这么的多. 嗯,先自我介绍哈吧,我是从云南的大山里走出来的孩子,什么样的大山,就是到 ...
- java微信开发框架wechat4j入门教程
wechat4j What is wechat4j? wechat develop framework for java(微信开发框架JAVA版,最简单易用微信开发框架) wechat4j可以用来干什 ...
- web api post注意事项
黄色笑话 近期一个项目需要使用到web api 在使用过程中,对应get请求方式的使用基本没出什么问题 但是对于post请求状况百出. 今将遇到的的问题列出.以作借鉴. 问题 -----post方式 ...
- JavaScript基础11——js的全局函数
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title> ...
- SharePoint List来做项目管理
其实这是一个常见的问题,已经不仅仅只是一次用SharePoint List来做项目管理了. 核心 1. SharePoint List Lookup自己来实现项目的父子关系 2. 权限控制,直接控制在 ...
- Retrofit源码设计模式解析(下)
本文将接着<Retrofit源码设计模式解析(上)>,继续分享以下设计模式在Retrofit中的应用: 适配器模式 策略模式 观察者模式 单例模式 原型模式 享元模式 一.适配器模式 在上 ...