LeetCode 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:

[[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 11, because the island 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 not exceed 50.

 


 

題目標簽:Array

  題目給了我們一個 2d grid array, 讓我們找到所有島中區域最大的一個,返回區域值。0代表海洋,1代表陸地。陸地與陸地相連,只能是橫向和縱向,不可以斜着。

  因為只能橫向和縱向相連,所以每一個cell 只能是4個方向延伸,左 上 右 下。

  這道題目要用到Depth-first Search,遍歷2d array,遇到1的時候,就利用dfs把這個島的區域大小找全。我的dps順序是 左,上,右,下。在遞歸dfs之前,要把目前的cell

  設為0,是為了避免dfs又往回走,每一個數過的cell,就不需要在重復走了。

 

  題外話:最近因為看不了極限挑戰,所以這幾天看了東方衛視的另一個節目 <夢想改造家4> , 挺好看的,特別是第4集。各位程序猿休息的時候可以看看!誰都不是一座孤島!加油刷題!

 

 

Java Solution:

Runtime beats 53.35% 

完成日期:10/22/2017

關鍵詞:Array

關鍵點:DFS

 1 class Solution 
 2 {
 3     public int maxAreaOfIsland(int[][] grid) 
 4     {
 5         int max_area = 0;
 6         
 7         for(int i=0; i<grid.length; i++)
 8         {
 9             for(int j=0; j<grid[0].length; j++)
10             {
11                 if(grid[i][j] == 1)
12                     max_area = Math.max(max_area, dfs(grid, i, j));
13             }
14         }
15         
16         return max_area;
17     }
18     
19     public int dfs(int[][] grid, int i, int j)
20     {
21         // if i or j is invalid or grid is 0, just return 0
22         if( i < 0 || i >= grid.length || j < 0 || j >= grid[0].length || grid[i][j] == 0)
23             return 0;
24         
25         // do dfs to its 4 direction cell when value is 1
26         int tempMaxArea = 1;    
27         grid[i][j] = 0; // set current cell to 0 to prevent dfs coming back
28         
29         // order is left, top, right, bottom
30         tempMaxArea += dfs(grid, i, j-1) + dfs(grid, i-1, j) + dfs(grid, i, j+1) + dfs(grid, i+1, j);
31         
32         return tempMaxArea;
33     }
34 }

參考資料:

https://discuss.leetcode.com/topic/106301/java-c-straightforward-dfs-solution

 

LeetCode 題目列表 - LeetCode Questions List

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM