Leetcode|DFS|695. 岛屿的最大面积

2021-09-22 11:21:38 浏览数 (1)

1 DFS

代码语言:javascript复制
class Solution {
public:
    int row, col, count;
    int maxcnt = 0;
    void dfs(vector<vector<int>>& grid, int r, int c) {
        if (r < 0 || c < 0 || r >= row || c >= col || grid[r][c] != 1) return;
        grid[r][c] = 0;
        count  ;
        
        dfs(grid, r   1, c);
        dfs(grid, r - 1, c);
        dfs(grid, r, c   1);
        dfs(grid, r, c - 1);
    }

    int maxAreaOfIsland(vector<vector<int>>& grid) {
        row = grid.size();
        col = grid[0].size();
        for (int i = 0; i < row; i  )
            for (int j = 0; j < col; j  ) {
                if (grid[i][j] == 1) {
                    count = 0;
                    dfs(grid, i, j);
                    maxcnt = max(maxcnt, count);
                }
            }
        return maxcnt;
    }
};
dfs

0 人点赞