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.
方法一: breadth first search
class Solution {
public:
int maxAreaOfIsland(vector<vector<int>>& grid) {
int nrow = grid.size();
int ncol = grid[0].size();
int maxsum = 0;
for (int i = 0; i < nrow; i++) {
for (int j = 0; j < ncol; j++) {
if (grid[i][j] == 1) {
int sum = 0;
queue<pair<int, int>> q;
q.push({i, j});
grid[i][j] = 0;
while (!q.empty()) {
auto pixel = q.front();
int r = pixel.first;
int c = pixel.second;
q.pop();
sum++;
if (r - 1 >= 0 && grid[r - 1][c] == 1) {
q.push({r - 1, c});
grid[r - 1][c] = 0;
}
if (c - 1 >= 0 && grid[r][c - 1] == 1) {
q.push({r, c - 1});
grid[r][c - 1] = 0;
}
if (r + 1 < nrow && grid[r + 1][c] == 1) {
q.push({r + 1, c});
grid[r + 1][c] = 0;
}
if (c + 1 < ncol && grid[r][c + 1] == 1) {
q.push({r, c + 1});
grid[r][c + 1] = 0;
}
}
if (sum > maxsum) {
maxsum = sum;
}
}
}
}
return maxsum;
}
};
方法二: depth first search
class Solution {
public:
int maxAreaOfIsland(vector<vector<int>>& grid) {
int nrow = grid.size();
int ncol = grid[0].size();
int maxsum = 0;
for (int i = 0; i < nrow; i++) {
for (int j = 0; j < ncol; j++) {
if (grid[i][j] == 1) {
int sum = maxArea(grid, i, j);
if (sum > maxsum) {
maxsum = sum;
}
}
}
}
return maxsum;
}
int maxArea(vector<vector<int>>& grid, int r, int c) {
int nrow = grid.size();
int ncol = grid[0].size();
int sum = 1;
grid[r][c] = 0;
if (r - 1 >= 0 && grid[r - 1][c] == 1) {
sum += maxArea(grid, r - 1, c);
}
if (c - 1 >= 0 && grid[r][c - 1] == 1) {
sum += maxArea(grid, r, c - 1);
}
if (r + 1 < nrow && grid[r + 1][c] == 1) {
sum += maxArea(grid, r + 1, c);
}
if (c + 1 < ncol && grid[r][c + 1] == 1) {
sum += maxArea(grid, r, c + 1);
}
return sum;
}
};