Leetcode Brush title Record [java]--695 Max area of the island

Source: Internet
Author: User

First, preface

ii. 695 Max area of the island

Given a non-empty 2D array grid of 0 ' and 1 ' s, an island was a group of 1 ' s (representing land) connected 4- directionally (horizontal or vertical.) Assume all four edges of the grid is surrounded by water.

Find the maximum area of a 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 one, because the 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 is not exceed 50.

Three, the thinking of solving problems

Iterate through the array to find the area of each island, 22 as a ratio, and return the maximum value.

1 classSolution {2      Public intMaxareaofisland (int[] grid) {3         intMax_area = 0;4          for(inti = 0; i < grid.length; i++)5              for(intj = 0; J < Grid[0].length; J + +)6                 if(Grid[i][j] = = 1) Max_area =Math.max (Max_area, Areaofisland (grid, I, j));7         returnMax_area;8     }9     Ten      Public intAreaofisland (int[] Grid,intIintj) { One         if(I>=0 && i < grid.length && j>=0 && J < grid[0].length && Grid[i][j] = = 1){ AGRID[I][J] = 0; -             return1 + areaofisland (grid, I+1, J) + Areaofisland (grid, I-1, J) + Areaofisland (grid, I, j-1) + Areaofisland (grid, I, j+1); -         } the         return0; -     } -}

Leetcode Brush title Record [java]--695 Max area of the island

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.