695.|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.Solution:DFS 思路:
Find the maximum area of an island in the given 2D array. (If there is no island, the maximum area is 0.)
【695.|695. Max Area of Island】Time Complexity: O(mn) Space Complexity: O(mn)
Solution Code:
class Solution {
public int maxAreaOfIsland(int[][] grid) {
int maxArea = 0;
for (int i = 0;
i < grid.length;
i++) {
for (int j = 0;
j < grid[i].length;
j++) {
if (grid[i][j] == 1) {
int curArea = dfs(grid, i, j);
if (curArea > maxArea) {
maxArea = curArea;
}
}}
}
return maxArea;
}private int dfs(int[][] grid, int i, int j) {
if (i < 0 || i >= grid.length || j < 0 || j >= grid[i].length) {
return 0;
}
if (grid[i][j] == 0) {
return 0;
}
grid[i][j] = 0;
// set as visited
return 1 + dfs(grid, i - 1, j) + dfs(grid, i + 1, j) + dfs(grid, i, j - 1) + dfs(grid, i, j + 1);
}
}
推荐阅读
- Android|Android 清单文件的硬件加速android:hardwareAccelerated 慎重
- 051:指针练习(MyMax)
- numpy中np.nanmax和np.max的区别及坑
- 我们真的读懂鸡汤文了吗()
- softmax损失函数-交叉熵
- 【leetcode】数组
- Max|Max retries exceeded with URL错误解决方法
- 原创|通俗易懂!详解Softmax及求导过程、Python实现、交叉熵
- G-max第二期练习生打造计划圆满落幕,致逆流而上的你们
- 为什么不带参数的|为什么不带参数的 Math.max() 返回-Infinity