Find the maximum area of an island in the given 2D array. (If there is no island, the maximum area is 0.)
Copy [[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]]
Copy // 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;
}
Copy // 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;
}