# 695. Max Area of Island

Given a non-empty 2D array `grid` of 0's and 1's, an **island** is a group of `1`'s (representing land) connected 4-directionally (horizontal or vertical.) You may assume all four edges of the grid are surrounded by water.

Find the maximum area of an island in the given 2D array. (If there is no island, the maximum area is 0.)

**Example 1:**

```
[[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]]
```

Given the above grid, return `6`. Note the answer is not 11, because the island must be connected 4-directionally.

**Example 2:**

```
[[0,0,0,0,0,0,0,0]]
```

Given the above grid, return `0`.

**Note:** The length of each dimension in the given `grid` does not exceed 50.

```cpp
// DFS
void helper(vector<vector<int> >& grid, vector<vector<bool> >& visited, int i, int j, int& cur) {
    if (i < 0 || i >= grid.size() || j < 0 || j >= grid[0].size() || grid[i][j] != 1 || visited[i][j]) return;
    visited[i][j] = true;
    ++cur;
    helper(grid, visited, i + 1, j, cur);
    helper(grid, visited, i - 1, j, cur);
    helper(grid, visited, i, j + 1, cur);
    helper(grid, visited, i, j - 1, cur);
}
int maxAreaOfIsland(vector<vector<int>>& grid) { // time: O(m * n); space: O(m * n)
    if (grid.empty() || grid[0].empty()) return 0;
    int res = 0, m = grid.size(), n = grid[0].size();
    vector<vector<bool> > visited(m, vector<bool> (n, false));
    for (int i = 0; i < m; ++i) {
        for (int j = 0; j < n; ++j) {
            if (grid[i][j] == 1 && !visited[i][j]) {
                int cur = 0;
                helper(grid, visited, i, j, cur);
                res = max(res, cur);
            }
        }
    }
    return res;
}
```

```cpp
// BFS
int maxAreaOfIsland(vector<vector<int>>& grid) { // time: O(m * n); space: O(m * n)
    if (grid.empty() || grid[0].empty()) return 0;
    int res = 0, m = grid.size(), n = grid[0].size();
    vector<vector<bool> > visited(m, vector<bool> (n, false));
    vector<vector<int> > dirs({{1, 0}, {-1, 0}, {0, 1}, {0, -1}});
    for (int i = 0; i < m; ++i) {
        for (int j = 0; j < n; ++j) {
            if (grid[i][j] != 1) continue;
            int cnt = 0;
            queue<pair<int, int> > q({{i, j}});
            visited[i][j] = true;
            while (!q.empty()) {
                pair<int, int> t = q.front(); q.pop();
                res = max(res, ++cnt);
                for (auto dir : dirs) {
                    int x = t.first + dir[0], y = t.second + dir[1];
                    if (x < 0 || x >= m || y < 0 || y >= n || grid[x][y] != 1 || visited[x][y]) continue;
                    visited[x][y] = true;
                    q.push({x, y});
                }
            }
        }
    }
    return res;
}
```
