Open azl397985856 opened 2 days ago
DFS
- 从陆地出发,遍历该陆地所在的岛屿
- 从隶属于该岛屿的某一块陆地出发,向四个方向递归地进行DFS
- 每次递归对下标进行判断,以区域的边界作为递归边界
- 将已访问过的陆地置为0,以保证每块陆地只访问一次
- 递归地返回整块岛屿陆地面积
- 找出所有岛屿的最大值
javaScript
/**
* @param {number[][]} grid
* @return {number}
*/
var maxAreaOfIsland = function(grid) {
let x = grid.length;
let y = grid[0].length;
let max = 0;
// 遍历二维数组
for (let i = 0; i < x; i ++) {
for (let j = 0; j < y; j ++) {
if (grid[i][j] === 1) {
max = Math.max(max, areaOfIsland(grid, i, j, x, y));
}
}
}
return max;
};
var areaOfIsland = function(grid, i, j, x, y) {
// 判断边界条件
if(i < 0 || i >= x || j < 0 || j >= y || grid[i][j] === 0) {
return 0
}
let ans = 1;
// 将遍历过的岛屿标记为0
grid[i][j] = 0;
// 遍历岛屿四周
ans += areaOfIsland(grid, i + 1, j, x, y);
ans += areaOfIsland(grid, i - 1, j, x, y);
ans += areaOfIsland(grid, i, j + 1, x, y);
ans += areaOfIsland(grid, i, j - 1, x, y);
return ans;
}
class Solution:
def maxAreaOfIsland(self, grid: List[List[int]]) -> int:
if not grid:
return 0
rows, cols = len(grid), len(grid[0])
def bfs(i,j):
#queue = deque([(i,j)])
queue = deque()
queue.append([i,j])
grid[i][j] = 0
area = 0
while queue:
x, y = queue.popleft()
area += 1
for dx, dy in [(1,0),(-1,0),(0, 1),(0, -1)]:
nx, ny = x + dx, y+dy
if 0<= nx < rows and 0<= ny <cols and grid[nx][ny] == 1:
queue.append((nx,ny))
grid[nx][ny] = 0
return area
max_area = 0
for i in range(rows):
for j in range(cols):
if grid[i][j] == 1:
max_area = max(max_area, bfs(i,j))
return max_area
Time: O(m*n)
SpaceO(m*n)
695. 岛屿的最大面积
入选理由
暂无
题目地址
https://leetcode-cn.com/problems/max-area-of-island/
前置知识
暂无
题目描述