LeetCode # Array # Easy # 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.)

 

题目:给定一个 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来分),然后在查找小矩阵中的最大岛。

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

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

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

posted @ 2018-05-15 20:44  何以解忧,唯有撸代码  阅读(135)  评论(0编辑  收藏  举报