Skip to content
On this page

Max Area of Island

695. Max Area of Island

DFS

  1. loop through grid and store pair of i, j in set, where grid[i][j] == 1.
  2. do DFS, where everytime traverse a vaild value, remove it from the set, as well as grid.
cpp
set<pair<int,int>>st;
int maxAreaOfIsland(vector<vector<int>>& grid) {
    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)
                st.insert({i,j});
    while(!st.empty()){
        auto it = st.begin();
        int a = dfs(grid, it->first, it->second);         
        res = max(res, a);
    }

    return res;
}
int dfs(vector<vector<int>>& grid, int i, int j) {
    if(i >= grid.size() || j >= grid[0].size() || grid[i][j] == 0)
        return 0;
    grid[i][j] = 0;
    st.erase({i,j});
    int re = 0;
    re = 1 + dfs(grid, i+1, j) + dfs(grid, i, j+1) + dfs(grid, i-1, j) + dfs(grid, i, j-1);
    return re;
}

Released under the MIT License.