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
class Solution
{
public int maxAreaOfIsland(int[][] grid)
{
int max_area = 0; for(int i=0; i<grid.length; i++)
{
for(int j=0; j<grid[0].length; j++)
{
if(grid[i][j] == 1)
max_area = Math.max(max_area, dfs(grid, i, j));
}
} return max_area;
} public int dfs(int[][] grid, int i, int j)
{
// if i or j is invalid or grid is 0, just return 0
if( i < 0 || i >= grid.length || j < 0 || j >= grid[0].length || grid[i][j] == 0)
return 0; // do dfs to its 4 direction cell when value is 1
int tempMaxArea = 1;
grid[i][j] = 0; // set current cell to 0 to prevent dfs coming back // order is left, top, right, bottom
tempMaxArea += dfs(grid, i, j-1) + dfs(grid, i-1, j) + dfs(grid, i, j+1) + dfs(grid, i+1, j); return tempMaxArea;
}
}
参考资料:
https://discuss.leetcode.com/topic/106301/java-c-straightforward-dfs-solution
LeetCode 题目列表 - LeetCode Questions List