类似的网格题:
数学法 | 深度优先搜索DFS:力扣463. 岛屿的周长
深度优先搜索DFS | 广度优先搜索BFS:力扣200. 岛屿数量
思路:
dfs的定义是求一个岛屿的面积,超过边界和不为1的点都返回0,然后标记已经访问,对上左下右依次进行dfs,加到结果中。最后遍历所有的点,找出最大岛屿的面积
python代码如下:
class Solution:
def maxAreaOfIsland(self, grid: List[List[int]]) -> int:
#DFS
def dfs(i,j):
if i < 0 or i >= len(grid) or j < 0 or j >= len(grid[0]): #超过边界,返回0
return 0
if grid[i][j] != 1: #不为1,返回0
return 0
temp = 1
grid[i][j] = 2
for x,y in [[-1,0],[0,1],[1,0],[0,-1]]:
temp += dfs(i + x,j + y)
return temp
res = 0
for i in range(len(grid)):
for j in range(len(grid[0])):
if grid[i][j] == 1:
res = max(res,dfs(i,j))
return res
C++ 代码如下:
class Solution {
public:
int dfs(vector<vector<int>>& grid,int i,int j){
if (i < 0 || i >= grid.size() || j < 0 || j >= grid[0].size())
return 0;
if (grid[i][j] != 1)
return 0;
grid[i][j] = 2;
int temp = 1;
int dx[4] = {-1,0,1,0};
int dy[4] = {0,1,0,-1};
for (int k = 0;k < 4;k++){
temp += dfs(grid,i + dx[k], j + dy[k]);
}
return temp;
// vector> directions = {{-1,0},{0,1},{1,0},{0,-1}};
// for (auto tt : directions)
// temp += dfs(grid,i + tt[0],j + tt[1]);
// return temp;
}
int maxAreaOfIsland(vector<vector<int>>& grid) {
// DFS
int res = 0;
for (int i = 0; i < grid.size();i ++)
for (int j = 0;j < grid[0].size();j++)
if (grid[i][j] == 1)
res = max(res,dfs(grid,i,j));
return res;
}
};
时间复杂度:O(m * n ),m,n分别为grid的长、宽,每个网格最多访问一次
空间复杂度:O(m * n )