[LeetCode] 827. Making A Large Island
In a 2D grid of 0
s and 1
s, we change at most one 0
to a 1
.
After, what is the size of the largest island? (An island is a 4-directionally connected group of 1
s).
Example 1:
Input: [[1, 0], [0, 1]]
Output: 3
Explanation: Change one 0 to 1 and connect two 1s, then we get an island with area = 3.
Example 2:
Input: [[1, 1], [1, 0]]
Output: 4
Explanation: Change the 0 to 1 and make the island bigger, only one island with area = 4.
Example 3:
Input: [[1, 1], [1, 1]]
Output: 4
Explanation: Can't change any 0 to 1, only one island with area = 4.
Notes:
1 <= grid.length = grid[0].length <= 50
.0 <= grid[i][j] <= 1
.
这个题目我只能想到naive的做法, T: O((m*n)^2), 就是对每个 grid[i][j] == 0 的元素, 将其换为1, 然后用BFS来计算size, 一直循环, 找最大值, 如果没有0 的话返回m*n.
然后参考了这个T: O(m*n) 的做法. 思路就是最开始将grid扫一遍, 每次如果grid[i][j] == 1, 将该点及所有跟它相连的为1 的点, 标记为color, 然后将各个不同的island tag为不同颜色, 并且用d2来存color和这个color的island 的size, 思路和做法跟[LeetCode] 200. Number of Islands_ Medium tag: BFS一样, 只是需要标记color.
这样之后可以得到如上图所示的结果, 然后再将grid扫一遍, 这一次是针对 grid[i][j] == 0 的元素, 然后看四个邻居是否为1, 如果是的话将它的size加入到temp里面,只是要注意的是有可能同样颜色的可以是多个neig, 所以要用set来排除已经加入同样颜色的size了, 最后返回最大值即可.
1. Constraints
1) size of grid, [1*1] ~ [50*50]
2) element will only be 0 or 1
2. Ideas
DFS/BFS 用BFS, T: O(m*n) S: O(m*n)
3. Code
class Solution:
def largestIsland(self, grid):
def bfs(grid, d1, i, j, d2, dirs, color):
lr, lc, d1[(i, j)], queue, size = len(grid), len(grid[0]), color, collections.deque([(i,j)]), 1 while queue:
pr, pc = queue.popleft()
for c1, c2 in dirs:
nr, nc = c1 + pr , c2 + pc
if 0 <= nr < lr and 0 <= nc < lc and (nr, nc) not in d1:
d1[(nr, nc)] = color
queue.append((nr, nc))
size += 1
d2[color] = size
d1, d2, lr, lc , dirs, temp, color = {},{}, len(grid), len(grid[0]), [(0,1), (0,-1), (1, 0), (-1,0)], -1, 1
for i in range(lr):
for j in range(lc):
if grid[i][j] == 1 and (i,j) not in d1:
color += 1
bfs(grid, d1, i, j, d2, dirs, color) for i in range(lr):
for j in range(lc):
if grid[i][j] == 0:
colors = set()
for c1, c2 in dirs:
nr, nc = i+ c1, j + c2
if 0 <= nr < lr and 0 <= nc < lc and grid[nr][nc] == 1:
colors.add(d1[nr][nc])
s = sum(d2[color] for color in colors) + 1
temp = s if temp == -1 else max(temp, s)
return temp if temp != -1 else lr*lc
2)
class Solution(object):
def largestIsland(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
lr, lc, dirs, colorMap, ans, colorSize, queue, curColor = len(grid), len(grid[0]), [(1, 0), (-1, 0), (0, 1), (0, -1)], {}, 0, {}, collections.deque(), 0
# color all the islands and save the pos -> color in colorMap, color -> size in colorSize
for i in range(lr):
for j in range(lc):
if grid[i][j] == 1 and (i, j) not in colorMap:
size = 0
curColor += 1
queue.append((i, j))
colorMap[(i, j)] = curColor
while queue:
r, c = queue.popleft()
size += 1
for d1, d2 in dirs:
nr, nc = r + d1, c + d2
if 0 <= nr < lr and 0 <= nc < lc and (nr, nc) not in colorMap and grid[nr][nc] == 1:
queue.append((nr, nc))
colorMap[(nr, nc)] = curColor
colorSize[curColor] = size
ans = max(ans, size) #### to each i, j that grid[i][j] == 0 , put all neigbours that is 1 and add all the color in a set, sum all color sizes and max(ans, sizeSum)
for i in range(lr):
for j in range(lc):
if grid[i][j] == 0:
colorSet = set()
for d1, d2 in dirs:
nr, nc = i + d1, j + d2
if 0 <= nr < lr and 0 <= nc < lc and grid[nr][nc] == 1:
colorSet.add(colorMap[(nr, nc)])
ans = max(ans, 1 + sum(colorSize[color] for color in colorSet))
return ans
[LeetCode] 827. Making A Large Island的更多相关文章
- [LeetCode] 827. Making A Large Island 建造一个巨大岛屿
In a 2D grid of 0s and 1s, we change at most one 0 to a 1. After, what is the size of the largest is ...
- 【leetcode】827. Making A Large Island
题目如下: 解题思路:这个题目可以进行拆分成几个子问题.第一,求出island的数量,其实就是 200. Number of Islands,这个很简单,DFS或者BFS都能搞定:第二,除了求出isl ...
- LeetCode 695. Max Area of Island (岛的最大区域)
Given a non-empty 2D array grid of 0's and 1's, an island is a group of 1's (representing land) conn ...
- [Swift]LeetCode827. 最大人工岛 | Making A Large Island
In a 2D grid of 0s and 1s, we change at most one 0 to a 1. After, what is the size of the largest is ...
- [Leetcode]695. Max Area of Island
Given a non-empty 2D array grid of 0's and 1's, an island is a group of 1's (representing land) conn ...
- [LeetCode] 830. Positions of Large Groups_Easy tag: Two Pointers
In a string S of lowercase letters, these letters form consecutive groups of the same character. For ...
- 【leetcode】Max Area of Island
国庆中秋长假过完,又要开始上班啦.先刷个题目找找工作状态. Given a non-empty 2D array grid of 0's and 1's, an island is a group o ...
- Java实现 LeetCode 827 最大人工岛(DFS+暴力模拟)
827. 最大人工岛 在二维地图上, 0代表海洋, 1代表陆地,我们最多只能将一格 0 海洋变成 1变成陆地. 进行填海之后,地图上最大的岛屿面积是多少?(上.下.左.右四个方向相连的 1 可形成岛屿 ...
- [Leetcode]827.使用回溯+标记解决最大人工岛问题
在二维地图上, 0代表海洋, 1代表陆地,我们最多只能将一格 0 海洋变成 1变成陆地. 进行填海之后,地图上最大的岛屿面积是多少?(上.下.左.右四个方向相连的 1 可形成岛屿) 示例 1: 输入: ...
随机推荐
- 【python3】urllib.error.URLError: <urlopen error [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:777)>
在玩爬虫的时候,针对https ,需要单独处理.不然就会报错: 解决办法:引入 ssl 模块即可 核心代码 imort ssl ssl._create_default_https_context = ...
- Esper学习之十五:Pattern(二)
上一篇开始了新一轮语法——Pattern的讲解,一开始为大家普及了几个基础知识,其中有说到操作符.当时只是把它们都列举出来了,所以今天这篇就是专门详解这些操作符的,但是由于篇幅限制,本篇先会讲几个,剩 ...
- C++ sort函数用法 C中的qsort
需要包含#include <algorithm>MSDN中的定义: template<class RanIt> void sort(RanIt first, RanIt ...
- Android6.0中PowerManagerService分析
转自:http://blog.chinaunix.net/xmlrpc.php?r=blog/article&uid=30510400&id=5569393 概述 一直以来,电源管理是 ...
- Telnet IMAP Commands Note
http://busylog.net/telnet-imap-commands-note/ Telnet IMAP Commands Note https://www.cnblogs.com/qiu ...
- Elasticsearch学习之深入搜索三 --- best fields策略
1. 为帖子数据增加content字段 POST /forum/article/_bulk { "} } { "doc" : {"content" : ...
- 使用Speech SDK 5.1文字转音频
下载地址: http://www.microsoft.com/en-us/download/details.aspx?id=10121 SeppchSDK51.exe 语音合成引擎 SpeechSDK ...
- web.xml之context-param,listener,filter,servlet加载顺序及其周边
先以加载spring为例子看看加载顺序的作用: Spring加载可以利用ServletContextListener 实现,也可以采用load-on-startup Servlet 实现,但比如fil ...
- 深圳MPD大会,五大专题一会尽享
深圳MPD大会,五大专题一会尽享 2013年9月,深圳的高温将慢慢褪去,炎炎夏日也会变得稍微清凉一些.但9月It届的峰会活动却没有丝毫的锐减.9月7-8日深圳将迎来MPD大会2013的收官之站. MP ...
- Numpy基础学习与总结
Numpy类型学习 1.数组的表示 import numpy as np In [2]: #numpy核心是高维数组,库中的ndarray支持多维数组,同时提供了数值运算,可对向量矩阵进行运算 In ...