1. 程式人生 > >LeetCode # Array # Easy # 695. Max Area of Island

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

tco 其中 connect emp RR turn 查找 治法 spa

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