695. Max Area of Island

深搜1的位置,记录每个面积的大小,及时更新。

class Solution {
public:
    int n, m;
    int dx[4]={1,-1,0,0}, dy[4]={0,0,1,-1};
    int maxAreaOfIsland(vector<vector<int>>& grid) {
        n = grid.size(), m = grid[0].size();
        int ans = 0;
        for(int i = 0; i < n; i++){
            for(int j = 0 ; j < m; j++){
                if(grid[i][j] == 1){
                    int cnt = 0;
                    dfs(grid, i, j, cnt);
                    ans = max(ans, cnt);
                }
            }
        }
        return ans;
    }
    void dfs(vector<vector<int>>& grid, int u, int v, int &c){
        if(u >= n||v >= m || u < 0 || v < 0 || grid[u][v] == 0) return;
        c++;
        grid[u][v] = 0;
        for(int i = 0; i < 4; i++){
            int a = u + dx[i], b = v + dy[i];
            dfs(grid, a, b, c);
        }
        
    }
};

你可能感兴趣的:(LeetCode经典编程题,DFS)