码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode # Array # Easy # 695. Max Area of Island

时间:2018-05-15 22:45:49      阅读:161      评论:0      收藏:0      [点我收藏+]

标签:重复   查找   经典   connect   pre   ==   rect   合并   []   

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.)

 

题目:给定一个 0 1 矩阵,求其中的最大的岛的大小。

思路:有两种解法

1.遍历每个点,然后按照深度优先搜索DFS找最大的岛。

 1 class Solution {
 2     public int maxAreaOfIsland(int[][] grid) {
 3         int n = grid.length, m = grid[0].length;
 4         int max=0, count=0;
 5         for(int i =0;i<n;i++){
 6             for(int j = 0; j < m; j++){
 7                 if(grid[i][j] == 1){
 8                     count = numOfIsland(grid,i,j);
 9                 }
10                 max = Math.max(max, count);
11             }
12            
13         }
14         return max;
15     }
16 
17     private int numOfIsland(int[][] grid, int row ,int col){
18         if(row < 0 || row >  grid.length-1 || col <0 || col > grid[0].length-1 || grid[row][col] != 1){
19             return 0;
20         }
21         grid[row][col] = -1;
22         return 1+ numOfIsland(grid, row-1,col)+numOfIsland(grid, row+1,col)+numOfIsland(grid,row,col-1)+numOfIsland(grid,row,col+1);//DFS递归
23     }
24 }

这种思路是比较常见和经典的解法,但是在遍历查找邻居时,会重复计算。

更精确的解法应该是分治法。

2.将矩阵等分为四个小矩阵(行,列为奇数不能等分时,按照n/2 和 n-n/2来分),然后在查找小矩阵中的最大岛。

合并四个小矩阵,如果现在有小岛在原矩阵的中心,且合并后会与别的岛合并,这种特殊情况需要处理。

然后,比较合并后的岛的最大值。 

代码:这里留个坑,后面会补上。

LeetCode # Array # Easy # 695. Max Area of Island

标签:重复   查找   经典   connect   pre   ==   rect   合并   []   

原文地址:https://www.cnblogs.com/DongPingAn/p/9042946.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!