标签:class lan ice array vertica ret name version int
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 };
标签:class lan ice array vertica ret name version int
原文地址:http://www.cnblogs.com/xumh/p/7694248.html