Topic link: https://leetcode.com/problems/max-area-of-island
The original theme is as follows:
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.
The main idea of the topic is to give a two-dimensional array, and then consider an island as a group of horizontally and vertically connected `1'blocks, how many islands are the size of the islands, and find out the maximum area of these islands.
This problem can be transformed into the problem of finding the size of the largest connected block in a graph. There are many isolated islands in the graph, that is, there are many connected blocks. We need to traverse the whole graph to find the entrance of the connected block, then do a depth-first traversal from the entrance to find the size of the corresponding islands, and finally compare the islands to find the size of the largest islands.
The key point here is to record the points on the islands that have been visited in the DFS process. I record them by visited array. If I have not visited them, I set them to 0, and if I have visited them, I set them to 1.
Based on the above idea, the source code is given as follows:
class Solution {
public:
void dfs(int i, int j, int& area, vector<vector<int>>& grid) {
visited[i][j] = 1;
int n = grid.size();
int col = grid[i].size();
if (i-1 >= 0 && !visited[i-1][j] && grid[i-1][j]) {
dfs(i-1, j, ++area, grid);
}
if (j-1 >= 0 && !visited[i][j-1] && grid[i][j-1]) {
dfs(i, j-1, ++area, grid);
}
if (i+1 < n && !visited[i+1][j] && grid[i+1][j]) {
dfs(i+1, j, ++area, grid);
}
if (j+1 < col && !visited[i][j+1] && grid[i][j+1]) {
dfs(i, j+1, ++area, grid);
}
}
int maxAreaOfIsland(vector<vector<int>>& grid) {
int max = 0;
for (int i = 0; i < 50; i++) {
for(int j = 0; j < 50; j++) {
visited[i][j] = 0;
}
}
for (int i = 0; i < grid.size(); i++) {
for (int j = 0; j < grid[i].size(); j++) {
int area = 0;
if (!visited[i][j] && grid[i][j]) dfs(i, j, ++area, grid);
if (max < area) max = area;
}
}
return max;
}
private:
bool visited[50][50];
};