边工作边刷题: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 ...
随机推荐
- 在博客中使用MathJax写数学公式
前言 总结一些在博客园使用MathJax写数学公式的经验. 博客园 设置使用数学公式 进入你的博客:管理 > 选项 里面有个启用数学公式支持,选上后保存. 这时,你就可以在你的博客里写数学公式了 ...
- Maven多模块项目使用MyBatis Generator
开发环境: JDK:8u102 Maven:3.3.9 MySQL:5.7.10 MySQL Connector:5.1.40 IDE:IntelliJ IDEA 2016 MyBatis:3.4.1 ...
- linux shell 编程
1,获取命令执行的结果,字符串拼接(脚本最常使用的功能) cmd_result=$(date +%Y%b%d) //使用变量获取命令执行的结果 或者 cmd_result=`date ...
- 浅谈一下缓存策略以及memcached 、redis区别
缓存策略三要素:缓存命中率 缓存更新策略 最大缓存容量.衡量一个缓存方案的好坏标准是:缓存命中率.缓存命中率越高,缓存方法设计的越好. 三者之间的关系为:当缓存到达最大的缓存容量时,会触发缓存更 ...
- Wechat4j之Hello world——使用wechat4j快速开发java版微信公众号
Wechat4j是一个开源的java微信开发框架,是目前最简单易用的java微信开发框架. 项目地址:https://github.com/sword-org/wechat4j Wechat4j.ja ...
- swift学习笔记之-析构过程
//析构过程deist import UIKit /*析构过程(Deinitialization):析构器只适用于类类型,当一个类的实例被释放之前,析构器会被立即调用.析构器用关键字deinit来标示 ...
- SharePoint 2013 调用WCF服务简单示例
内容比较简单,主要记录自己使用SharePoint 2013WCF服务遇到的小问题和小经验,分享给大家,希望能够给需要的人有所帮助.好吧,进入正题! 第一部分 SharePoint 2013调用自带W ...
- Android-ListView类
ListView组件在应用程序中可以说是不可或缺的一部分,ListView主要是显示列表数据,同时可以滚动查看,这篇博客主要是对ListView的基本用法进行说明,后面会依次对ListView点击动态 ...
- 如何在Eclipse卸载之前添加的android 的 ADT
Android开发环境配置中,怎么卸载ADT? 在Android开发环境配置中,可能会遇到很多问题,其中ADT安装失败需要卸载,怎么卸载呢?下面讲一种方法,希望能够对你有所帮助. 我采用的是Eclip ...
- JAVA EE(简述)
一.平台概述 JavaEE的全称是Java Enterprise Edition,它是一个开发分布式企业级应用的规范和标准 Java 平台三个版本: Java ME(Java Micro Edit ...