695. 岛屿的最大面积
题目描述
给你一个大小为 m x n
的二进制矩阵 grid
。
岛屿 是由一些相邻的 1
(代表土地) 构成的组合,这里的「相邻」要求两个 1
必须在 水平或者竖直的四个方向上 相邻。你可以假设 grid
的四个边缘都被 0
(代表水)包围着。
岛屿的面积是岛上值为 1
的单元格的数目。
计算并返回 grid
中最大的岛屿面积。如果没有岛屿,则返回面积为 0
。
示例 1:
输入: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]] 输出:6 解释:答案不应该是11
,因为岛屿只能包含水平或垂直这四个方向上的1
。
示例 2:
输入:grid = [[0,0,0,0,0,0,0,0]] 输出:0
提示:
m == grid.length
n == grid[i].length
1 <= m, n <= 50
grid[i][j]
为0
或1
方法一:DFS
我们可以遍历每一个格子
时间复杂度
java
class Solution {
private int m;
private int n;
private int[][] grid;
public int maxAreaOfIsland(int[][] grid) {
m = grid.length;
n = grid[0].length;
this.grid = grid;
int ans = 0;
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
ans = Math.max(ans, dfs(i, j));
}
}
return ans;
}
private int dfs(int i, int j) {
if (grid[i][j] == 0) {
return 0;
}
int ans = 1;
grid[i][j] = 0;
int[] dirs = {-1, 0, 1, 0, -1};
for (int k = 0; k < 4; ++k) {
int x = i + dirs[k], y = j + dirs[k + 1];
if (x >= 0 && x < m && y >= 0 && y < n) {
ans += dfs(x, y);
}
}
return ans;
}
}
cpp
class Solution {
public:
int maxAreaOfIsland(vector<vector<int>>& grid) {
int m = grid.size(), n = grid[0].size();
int dirs[5] = {-1, 0, 1, 0, -1};
int ans = 0;
function<int(int, int)> dfs = [&](int i, int j) {
if (grid[i][j] == 0) {
return 0;
}
int ans = 1;
grid[i][j] = 0;
for (int k = 0; k < 4; ++k) {
int x = i + dirs[k], y = j + dirs[k + 1];
if (x >= 0 && x < m && y >= 0 && y < n) {
ans += dfs(x, y);
}
}
return ans;
};
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
ans = max(ans, dfs(i, j));
}
}
return ans;
}
};
ts
function maxAreaOfIsland(grid: number[][]): number {
const m = grid.length;
const n = grid[0].length;
const dirs = [-1, 0, 1, 0, -1];
const dfs = (i: number, j: number): number => {
if (grid[i][j] === 0) {
return 0;
}
let ans = 1;
grid[i][j] = 0;
for (let k = 0; k < 4; ++k) {
const [x, y] = [i + dirs[k], j + dirs[k + 1]];
if (x >= 0 && x < m && y >= 0 && y < n) {
ans += dfs(x, y);
}
}
return ans;
};
let ans = 0;
for (let i = 0; i < m; ++i) {
for (let j = 0; j < n; ++j) {
ans = Math.max(ans, dfs(i, j));
}
}
return ans;
}
python
class Solution:
def maxAreaOfIsland(self, grid: List[List[int]]) -> int:
def dfs(i: int, j: int) -> int:
if grid[i][j] == 0:
return 0
ans = 1
grid[i][j] = 0
dirs = (-1, 0, 1, 0, -1)
for a, b in pairwise(dirs):
x, y = i + a, j + b
if 0 <= x < m and 0 <= y < n:
ans += dfs(x, y)
return ans
m, n = len(grid), len(grid[0])
return max(dfs(i, j) for i in range(m) for j in range(n))