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
.
Approach 1:
1 public int maxAreaOfIsland(int[][] grid) { 2 if (grid == null || grid.length == 0) { 3 return 0; 4 } 5 int m = grid.length; 6 int n = grid[0].length; 7 int max = 0; 8 for (int i = 0; i < m; i++) { 9 for (int j = 0; j < n; j++) { 10 if (grid[i][j] == 1) { 11 int area = dfs(grid, i, j, m, n, 0); 12 max = Math.max(area, max); 13 } 14 } 15 } 16 return max; 17 } 18 19 int dfs(int[][] grid, int i, int j, int m, int n, int area) { 20 if (i < 0 || i >= m || j < 0 || j >= n || grid[i][j] == 0) { 21 return area; 22 } 23 grid[i][j] = 0; 24 area++; 25 area = dfs(grid, i + 1, j, m, n, area); 26 area = dfs(grid, i, j + 1, m, n, area); 27 area = dfs(grid, i - 1, j, m, n, area); 28 area = dfs(grid, i, j - 1, m, n, area); 29 return area; 30 }
Approach 2:
1 class Solution { 2 public int maxAreaOfIsland(int[][] grid) { 3 int max_area = 0; 4 for(int i = 0; i < grid.length; i++) 5 for(int j = 0; j < grid[0].length; j++) 6 if(grid[i][j] == 1)max_area = Math.max(max_area, AreaOfIsland(grid, i, j)); 7 return max_area; 8 } 9 10 public int AreaOfIsland(int[][] grid, int i, int j){ 11 if( i >= 0 && i < grid.length && j >= 0 && j < grid[0].length && grid[i][j] == 1){ 12 grid[i][j] = 0; 13 return 1 + AreaOfIsland(grid, i+1, j) + AreaOfIsland(grid, i-1, j) + AreaOfIsland(grid, i, j-1) + AreaOfIsland(grid, i, j+1); 14 } 15 return 0; 16 } 17 }
原文地址:https://www.cnblogs.com/beiyeqingteng/p/10349597.html
时间: 2024-11-10 23:57:19