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 };
原文地址:https://www.cnblogs.com/dapeng-bupt/p/7894818.html