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.
思路:深度优先搜索。从第一行第一个开始遍历整个数组,如果某个位置的值是 1 ,那么就开始深度优先搜索。
在深度优先搜索中,我们先要看看与该位置连通有几种可能的情况,很明显是4种,即上下左右。所以我们得用
个循环来遍历这四种可能的情况。如果上或下或左或右的值是1,我们就用递归函数递归上或下或左或右的位置,
求解他们连通的情况。
1 class Solution { 2 private int sum = 0,maxSum = 0; 3 public int maxAreaOfIsland(int[][] grid) { 4 for (int i=0;i<grid.length;i++){ 5 for (int j=0;j<grid[i].length;j++){ 6 if (grid[i][j]==1){ 7 sum = 0; 8 dfs(grid,i,j); 9 } 10 } 11 } 12 return maxSum; 13 } 14 private void dfs(int[][] grid,int i,int j){ 15 sum +=grid[i][j]; 16 grid[i][j]= 0; 17 if (i-1>=0&&grid[i-1][j]==1) 18 dfs(grid,i-1,j); 19 if (i+1<grid.length&&grid[i+1][j]==1) 20 dfs(grid,i+1,j); 21 if (j-1>=0&&grid[i][j-1]==1) 22 dfs(grid,i,j-1); 23 if (j+1<grid[i].length&&grid[i][j+1]==1) 24 dfs(grid,i,j+1); 25 if (sum>maxSum){ 26 maxSum = sum; 27 } 28 29 } 30 }