首页 > 其他 > 详细

695. Max Area of Island

时间:2017-10-19 20:20:00      阅读:391      评论:0      收藏:0      [点我收藏+]

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:

1 [[0,0,1,0,0,0,0,1,0,0,0,0,0],
2  [0,0,0,0,0,0,0,1,1,1,0,0,0],
3  [0,1,1,0,1,0,0,0,0,0,0,0,0],
4  [0,1,0,0,1,1,0,0,1,0,1,0,0],
5  [0,1,0,0,1,1,0,0,1,1,1,0,0],
6  [0,0,0,0,0,0,0,0,0,0,1,0,0],
7  [0,0,0,0,0,0,0,1,1,1,0,0,0],
8  [0,0,0,0,0,0,0,1,1,0,0,0,0]]

 

Solution1:

 1 //============================================================================
 2 // Name        : Max.cpp
 3 // Author      : xmh
 4 // Version     :
 5 // Copyright   : Your copyright notice
 6 // Description : DFS / BFS
 7 //============================================================================
 8 
 9 #include <vector>
10 #include <iostream>
11 #include <algorithm>
12 using namespace std;
13 
14 class Solution {
15 public:
16     int maxAreaOfIsland(vector<vector<int>>& grid) {
17         int max_area = 0;
18         for(int i = 0; i < grid.size(); i++)
19             for(int j = 0; j < grid[0].size(); j++)
20                 if(grid[i][j] == 1)max_area = max(max_area, AreaOfIsland(grid, i, j));
21         return max_area;
22     }
23 
24     int AreaOfIsland(vector<vector<int>>& grid, int i, int j){
25         if( i >= 0 && i < grid.size() && j >= 0 && j < grid[0].size() && grid[i][j] == 1){
26             grid[i][j] = 0;
27             return 1 + AreaOfIsland(grid, i+1, j) + AreaOfIsland(grid, i-1, j) + AreaOfIsland(grid, i, j-1) + AreaOfIsland(grid, i, j+1);
28         }
29         return 0;
30     }
31 };

 

695. Max Area of Island

原文:http://www.cnblogs.com/xumh/p/7694248.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!