【题目】
岛屿矩阵,0表示海洋,数字表示岛屿面积,只有上下左右代表岛屿相连,对角线不算。
求问海洋里最大的岛屿面积
You are given an m x n
binary matrix grid
. 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.
The area of an island is the number of cells with a value 1
in the island.
Return the maximum area of an island in grid
. If there is no island, return 0
.
Example 1:
Input: grid = [[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]] Output: 6 最大面积6 Explanation: The answer is not 11, because the island must be connected 4-directionally.
Example 2:
Input: grid = [[0,0,0,0,0,0,0,0]] Output: 0
【思路】
用DFS,遍历上下左右是否相连四种情况。
注意边界情况,grid的length。
当遇到海洋时,结束。因此对访问计算过的岛屿标记成海洋。
【代码】
class Solution { public int maxAreaOfIsland(int[][] grid) { int ans=0; for(int i=0;i<grid.length;i++){ for(int j=0;j<grid[0].length;j++) { if (grid[i][j]!=0){ ans=Math.max(dfs(grid,i,j,0),ans);}}} return ans; } public int dfs(int[][] grid,int i,int j,int ans){ if (i < 0 || i >= grid.length || j < 0 || j >= grid[0].length || grid[i][j] == 0) { return ans; } ans+=grid[i][j]; grid[i][j]=0;
//已经遍历过的岛屿标记为0海洋 ans=dfs(grid,i+1,j,ans); ans=dfs(grid,i-1,j,ans); ans=dfs(grid,i,j+1,ans); ans=dfs(grid,i,j-1,ans);
//上下左右,ans调用累加 return ans; } }