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 1s).

Example 1:

  1. Input: [[1, 0], [0, 1]]
  2. Output: 3
  3. Explanation: Change one 0 to 1 and connect two 1s, then we get an island with area = 3.

Example 2:

  1. Input: [[1, 1], [1, 0]]
  2. Output: 4
  3. Explanation: Change the 0 to 1 and make the island bigger, only one island with area = 4.

Example 3:

  1. Input: [[1, 1], [1, 1]]
  2. Output: 4
  3. 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.

这道题在只有0和1的矩阵中用相连的1来表示小岛,现在说是有一个把0变为1的机会,这样原本不相邻的岛就有可能变的相邻了,从而组成一个更大的岛,让求出可能组成的最大的岛屿的面积,也就是相连的1的个数。在 LeetCode 中关于岛屿的题其实也做过许多,比如 [Number of Distinct Islands II](http://www.cnblogs.com/grandyang/p/8542820.html),[Max Area of Island](http://www.cnblogs.com/grandyang/p/7712724.html),[Number of Distinct Islands](http://www.cnblogs.com/grandyang/p/7698778.html),[Number of Islands II](http://www.cnblogs.com/grandyang/p/5190419.html),和 [Number of Islands](http://www.cnblogs.com/grandyang/p/4402656.html)。其实大多题目的本质都是用 DFS 或者 BFS 去遍历所有相连的1,当然这道题也不例外。博主最开始的想法是首先用 DFS 来找出每个岛屿,然后把同一个岛屿的位置坐标都放到同一个 HashSet 中,这样就有了很多 HashSet,然后遍历所有的0的位置,对每个0位置,遍历其周围4个邻居,然后看邻居位置有没有属于岛屿的,有的话就把该岛屿的 HashSet 编号记录下来,遍历完4个邻居后,在把所有的相连的岛屿中的1个数加起来(因为 HashSet 可以直接求出集合中数字的总个数),每次更新结果 res 即可。这种方法是可以通过 OJ 的,速度还比下面展示的两种方法要快,就是代码比较长,没有下面方法的简洁,这里就不贴了。下面的这两种方法其实都是从每个0开始处理,先把0替换成1,然后再用 DFS 来找所有相连的1的个数,具体如何找就跟之前的岛屿的题目没啥区别了,这里就不细讲了,参见代码如下:


解法一:

  1. class Solution {
  2. public:
  3. int largestIsland(vector<vector<int>>& grid) {
  4. int m = grid.size(), n = grid[0].size(), res = 0;
  5. bool hasZero = false;
  6. for (int i = 0; i < m; ++i) {
  7. for (int j = 0; j < n; ++j) {
  8. if (grid[i][j] == 1) continue;
  9. grid[i][j] = 1;
  10. vector<vector<bool>> visited(m, vector<bool>(n));
  11. res = max(res, helper(grid, i, j, visited));
  12. if (res == m * n) return res;
  13. grid[i][j] = 0;
  14. hasZero = true;
  15. }
  16. }
  17. return hasZero ? res : m * n;
  18. }
  19. int helper(vector<vector<int>>& grid, int i, int j, vector<vector<bool>>& visited) {
  20. int m = grid.size(), n = grid[0].size();
  21. if (i < 0 || i >= m || j < 0 || j >= n || grid[i][j] == 0 || visited[i][j]) return 0;
  22. visited[i][j] = true;
  23. return 1 + helper(grid, i - 1, j , visited) + helper(grid, i + 1, j , visited) + helper(grid, i, j - 1, visited) + helper(grid, i, j + 1, visited);
  24. }
  25. };

当然我们也可以用 BFS 来找所有相连的1的个数,整个的解题思路和上面的解法并没有什么不同,并不难理解,这可能就是论坛上会有人质疑这道题不应该标为 Hard 的原因,参见代码如下:


解法二:

  1. class Solution {
  2. public:
  3. int largestIsland(vector<vector<int>>& grid) {
  4. int m = grid.size(), n = grid[0].size(), res = 0;
  5. bool hasZero = false;
  6. vector<int> dirX{0, -1, 0, 1}, dirY{-1, 0, 1, 0};
  7. for (int i = 0; i < m; ++i) {
  8. for (int j = 0; j < n; ++j) {
  9. if (grid[i][j] == 1) continue;
  10. vector<vector<bool>> visited(m, vector<bool>(n));
  11. queue<int> q{{i * n + j}};
  12. int sum = 0;
  13. while (!q.empty()) {
  14. int t = q.front(); q.pop();
  15. ++sum;
  16. for (int k = 0; k < 4; ++k) {
  17. int x = t / n + dirX[k], y = t % n + dirY[k];
  18. if (x < 0 || x >= m || y < 0 || y >= n || grid[x][y] == 0 || visited[x][y]) continue;
  19. visited[x][y] = true;
  20. q.push(x * n + y);
  21. }
  22. }
  23. res = max(res, sum);
  24. if (res == m * n) return res;
  25. hasZero = true;
  26. }
  27. }
  28. return hasZero ? res : m * n;
  29. }
  30. };

Github 同步地址:

https://github.com/grandyang/leetcode/issues/827

类似题目:

Number of Distinct Islands II

Max Area of Island

Number of Distinct Islands

Number of Islands II

Number of Islands

参考资料:

https://leetcode.com/problems/making-a-large-island/

https://leetcode.com/problems/making-a-large-island/discuss/313787/Two-java-solutions

https://leetcode.com/problems/making-a-large-island/discuss/127256/DFS-JAVA-AC-CONCISE-SOLUTION

https://leetcode.com/problems/making-a-large-island/discuss/127015/C%2B%2B-O(n*m)-15-ms-colorful-islands

[LeetCode All in One 题目讲解汇总(持续更新中...)](https://www.cnblogs.com/grandyang/p/4606334.html)

[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之深度优先搜索(DFS)专题-695. 岛屿的最大面积(Max Area of Island)

    Leetcode之深度优先搜索(DFS)专题-695. 岛屿的最大面积(Max Area of Island) 深度优先搜索的解题详细介绍,点击 给定一个包含了一些 0 和 1的非空二维数组 grid ...

  4. [LeetCode] 496. Next Greater Element I 下一个较大的元素 I

    You are given two arrays (without duplicates) nums1 and nums2 where nums1’s elements are subset of n ...

  5. [LeetCode] 503. Next Greater Element II 下一个较大的元素 II

    Given a circular array (the next element of the last element is the first element of the array), pri ...

  6. [LeetCode] 556. Next Greater Element III 下一个较大的元素 III

    Given a positive 32-bit integer n, you need to find the smallest 32-bit integer which has exactly th ...

  7. Leetcode之深度优先搜索(DFS)专题-200. 岛屿数量(Number of Islands)

    Leetcode之深度优先搜索(DFS)专题-200. 岛屿数量(Number of Islands) 深度优先搜索的解题详细介绍,点击 给定一个由 '1'(陆地)和 '0'(水)组成的的二维网格,计 ...

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

  9. [LeetCode] Search a 2D Matrix II 搜索一个二维矩阵之二

    Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the follo ...

随机推荐

  1. 解决原生javascript 缺少insertAfter的功能,非Jquery方法

    在现有的方法后插入一个新元素,你可能会想:既然有insertBefore方法,是不是也有一个相应的insertAfter()方法.很可惜,DOM没有提供方法.下面编写insertAfter函数,虽然D ...

  2. Flink之state processor api实践

    前不久,Flink社区发布了FLink 1.9版本,在其中包含了一个很重要的新特性,即state processor api,这个框架支持对checkpoint和savepoint进行操作,包括读取. ...

  3. redis延迟队列

    异步消息队列 Redis 的 list(列表) 数据结构常用来作为异步消息队列使用,使用rpush/lpush操作入队列, 使用 lpop 和 rpop 来出队列. > rpush notify ...

  4. 成都,我们来啦 | Dubbo 社区开发者日

    [关注 阿里巴巴云原生 公众号,回复关键词"报名",即可参与抽奖!] 活动时间:10 月 26 日 13:00 - 18:00 活动地点:成都市高新区交子大道中海国际中心 233 ...

  5. Java8新特性——StreamAPI 的使用

    StreamAPI的说明 Java8中有两大最为重要的改变.第一个是 Lambda 表达式:另外一个则是 Stream API. Stream API ( java.util.stream) 把真正的 ...

  6. War 包部署

    Springboot 进行war包部署,以及踩坑历险!!! https://www.jianshu.com/p/4c2f27809571 Springboot2项目配置(热部署+war+外部tomca ...

  7. [转载].NET ASP.NET 中web窗体(.aspx)利用ajax实现局部刷新

    之前开发的一套系统中用到了大量的 checkboxList 控件,但是每次选定之后都会刷新整个页面,用户体验很差,百度了之后查到这篇文章,尝试了一下可以实现,所以转载了过来,记录一下,也给其他有相同困 ...

  8. 【转】测试开发工程师必备软硬能力&高级测试开发工程师需要具备什么能力?

    对于测试的基本知识,可以查看软件测试相关书籍 对于在公司成为一位优秀的测试开发工程师,我觉得下面这篇文章涉及到的是我们需要的,稍微进行改动https://blog.csdn.net/sinat_210 ...

  9. express的安装和新建项目流程!

    1.安装脚手架工具:npm install express express-generator -g 2.-h 参数可以列出所有可用的命令行参数 3.创建项目:express  -e firstexp ...

  10. echarts折线图上下颜色渐变样式

    // 折线图let lineChart = echarts.init(document.getElementById('lineChart'));let lineOption = { title: { ...