695. Max Area of Island
Posted lvbbg
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了695. Max Area of Island相关的知识,希望对你有一定的参考价值。
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的主要内容,如果未能解决你的问题,请参考以下文章
695. Max Area of Island@python
[leetcode-695-Max Area of Island]