695. 岛屿的最大面积(DFS)

 

labuladong 题解思路
难度中等

给你一个大小为 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

 

 

class Solution:
    def maxAreaOfIsland(self, grid: List[List[int]]) -> int:

        n = len(grid)
        m = len(grid[0])
        def dfs(grid,i,j):
            if i < 0 or j < 0 or i >= n or j >=m or  grid[i][j] == 0:
                return 0
            grid[i][j] = 0
            return 1 + dfs(grid,i+1,j) + dfs(grid,i-1,j) + dfs(grid,i,j-1) + dfs(grid,i,j+1)

        cnt = 0
        for i in range(n):
            for j in range(m):
                if grid[i][j] == 1:
                    cur = dfs(grid,i,j)
                    cnt = max(cnt,cur)
        return cnt

 

 

 

class Solution {
public:
    vector<vector<int>> dirs = {{1,0},{-1,0},{0,1},{0,-1}};
    void dfs(int& area,int i, int j, vector<vector<int>>& grid) {
        if( i<0 || i>=grid.size() || j<0 || j >= grid[0].size()) {
            return;
        }
        if (grid[i][j] == 0) {
            return;
        }
        grid[i][j] = 0;
        area++;
        for(auto ch : dirs) {
            dfs(area,i+ch[0],j+ch[1],grid);
        }
    }
    int maxAreaOfIsland(vector<vector<int>>& grid) {

        int cnt = 0;
        for(int i = 0;i < grid.size();i++) {
            for (int j = 0 ; j < grid[0].size();j++) {
                if(grid[i][j]==1) {
                    int area = 0;
                    dfs(area,i,j,grid);
                    cnt = max(cnt,area);
                }
            }
        }
        return cnt;
    }
};

 

 
posted @ 2022-05-29 12:58  乐乐章  阅读(27)  评论(0编辑  收藏  举报