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 island? (An island is a 4-directionally connected group of 1s).

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的更多相关文章

  1. [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 ...

  2. 【leetcode】827. Making A Large Island

    题目如下: 解题思路:这个题目可以进行拆分成几个子问题.第一,求出island的数量,其实就是 200. Number of Islands,这个很简单,DFS或者BFS都能搞定:第二,除了求出isl ...

  3. 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 ...

  4. [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 ...

  5. [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 ...

  6. [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 ...

  7. 【leetcode】Max Area of Island

    国庆中秋长假过完,又要开始上班啦.先刷个题目找找工作状态. Given a non-empty 2D array grid of 0's and 1's, an island is a group o ...

  8. Java实现 LeetCode 827 最大人工岛(DFS+暴力模拟)

    827. 最大人工岛 在二维地图上, 0代表海洋, 1代表陆地,我们最多只能将一格 0 海洋变成 1变成陆地. 进行填海之后,地图上最大的岛屿面积是多少?(上.下.左.右四个方向相连的 1 可形成岛屿 ...

  9. [Leetcode]827.使用回溯+标记解决最大人工岛问题

    在二维地图上, 0代表海洋, 1代表陆地,我们最多只能将一格 0 海洋变成 1变成陆地. 进行填海之后,地图上最大的岛屿面积是多少?(上.下.左.右四个方向相连的 1 可形成岛屿) 示例 1: 输入: ...

随机推荐

  1. H5 password自动记录取消

    最近完成一个项目时需要取消谷歌浏览器的密码自动填充功能,为了用户方便,大多浏览器都有保存某个网站的密码并在后面再打开这个网站且需要输入密码的时候自动填充.这个功能是方便,但是我们有时候不需要使用这个功 ...

  2. filter对数组和对象的过滤

    1,对数组的过滤 let arr = ['1', '2', '3'] let b = arr.filter(val => val === '2') console.log(b) // ['2] ...

  3. sysbench 压力测试工具

    一.sysbench压力测试工具简介: sysbench是一个开源的.模块化的.跨平台的多线程性能测试工具,可以用来进行CPU.内存.磁盘I/O.线程.数据库的性能测试.目前支持的数据库有MySQL. ...

  4. POJ 2386 Lake Counting(搜索联通块)

    Lake Counting Time Limit: 1000MS Memory Limit: 65536K Total Submissions: 48370 Accepted: 23775 Descr ...

  5. python unittest框架中doCleanups妙用

    偶看unittest官方文档中,发现一个很好用的功能函数doCleanups,看看官方是怎么解释的: doCleanups() This method is called unconditionall ...

  6. mysql概要(四)order by ,limit ,group by和聚合函数的特点,子查询

    1.order by 默认按升序排列(asc/desc),多字段排序 order by 字段 排序方式,字段2 排序方式,..: 在分组排序中,排序是对分组后的结果进行排序,而不是在组中进行排序. s ...

  7. BeanWrapper

    BeanWrapper是对Bean的包装,其接口中所定义的功能很简单包括设置获取被包装的对象,获取被包装bean的属性描述器,由于BeanWrapper接口是PropertyAccessor的子接口, ...

  8. git如何回滚当前修改的内容?

    git如何回滚当前修改的内容? 1.打开git gui,在工具栏上点击 commit ,选择 Revert Changes,  这里可以回滚单个文件: 2.一键回滚所有修改: 打开git gui,在工 ...

  9. Qt qDebug() 的使用方法

    在Qt程序调试的时候,经常需要打印一些变量,那么我们就需要使用qDebug()函数,这种函数有两种使用方法,如下所示: QString s = "Jack"; qDebug() & ...

  10. Solve Error: 'has incomplete type', foward declaration of 'class x'

    在C++的OOB编程中,有时候我们会遇到这样的错误Error: 'has incomplete type',forward declaration of 'class x',那么是什么原因引起的这个问 ...