zoukankan      html  css  js  c++  java
  • 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) connected 4-directionally (horizontal or vertical.) You may assume all four edges of the grid are surrounded by water.

    Find the maximum area of an island in the given 2D array. (If there is no island, the maximum area is 0.)

    Example 1:

    [[0,0,1,0,0,0,0,1,0,0,0,0,0],
     [0,0,0,0,0,0,0,1,1,1,0,0,0],
     [0,1,1,0,1,0,0,0,0,0,0,0,0],
     [0,1,0,0,1,1,0,0,1,0,1,0,0],
     [0,1,0,0,1,1,0,0,1,1,1,0,0],
     [0,0,0,0,0,0,0,0,0,0,1,0,0],
     [0,0,0,0,0,0,0,1,1,1,0,0,0],
     [0,0,0,0,0,0,0,1,1,0,0,0,0]]
    

    Given the above grid, return 6. Note the answer is not 11, because the island must be connected 4-directionally.

    Example 2:

    [[0,0,0,0,0,0,0,0]]

    Given the above grid, return 0.

    Note: The length of each dimension in the given grid does not exceed 50.

    题目要求最大的连续1的数量,可以用递归很简洁的解决问题,但是注意一个问题,需要处理好已经访问的元素,否则会造成重复访问以及死循环,本文采用的方法是将已经访问过的位置标记为0,代码如下:

     1 class Solution {
     2 public:
     3     int maxAreaOfIsland(vector<vector<int>>& grid) 
     4     {
     5        //用递归的思路
     6         int max_area = 0;
     7         int m = grid.size(), n = grid[0].size();
     8         for (int i = 0; i < m; i++)
     9             for (int j = 0; j < n; j++)
    10                 if (grid[i][j] == 1)
    11                     max_area = max(max_area,AreaOfIsland(grid,i,j));
    12         return max_area;
    13     }
    14     
    15     int AreaOfIsland(vector<vector<int>>& grid, int i, int j)
    16     {
    17         if (i >= 0 && i < grid.size() && j>=0 && j < grid[0].size() && grid[i][j] == 1)
    18         {
    19                grid[i][j] = 0;
    20              return (1 + AreaOfIsland(grid, i+1, j) + AreaOfIsland(grid, i-1, j) + AreaOfIsland(grid, i ,j-1)
    21                    + AreaOfIsland(grid, i, j+1));
    22         }
    23         return 0;
    24     }
    25 };
  • 相关阅读:
    <a>與<link>的區別
    103_linux如何安装mysql数据库?
    102_Centos7在虚拟机上开机时出现黑屏,怎么解决?
    101_war和war exploded的区别
    100_linux中passwd文件的用户解析
    099_linux基础命令三
    098_linux基本操作命令二
    097_linux如何配置jdk路径
    096_如何将linux的IP地址转换成静态ip地址?
    078_ip地址.DNS,子网掩码,网关分别是什么,又有什么作用?
  • 原文地址:https://www.cnblogs.com/dapeng-bupt/p/7894818.html
Copyright © 2011-2022 走看看