题目:
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.
思路:
练手的DFS题目^_^。
代码:
class Solution {
public:
int maxAreaOfIsland(vector<vector<int>>& grid) {
int row_num = grid.size(), col_num = grid[0].size();
int max_area = 0, area;
for (int r = 0; r < row_num; ++r) {
for (int c = 0; c < col_num; ++c) {
if (grid[r][c] == 1) {
area = 0;
DFS(grid, r, c, area);
max_area = max(max_area, area);
}
}
}
return max_area;
}
private:
void DFS(vector<vector<int>> &grid, int r, int c, int &area) {
int row_num = grid.size(), col_num = grid[0].size();
if (r < 0 || r >= row_num || c < 0 || c >= col_num || grid[r][c] <= 0) {
return;
}
++area;
grid[r][c] = -1;
for (int d = 0; d < 4; ++d) {
DFS(grid, r + delta[d][0], c + delta[d][1], area);
}
}
int delta[4][2] = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
};
本文介绍了一个寻找二维数组中最大岛屿面积的问题解决方案。通过深度优先搜索(DFS)算法遍历矩阵,标记已访问过的陆地,并计算当前岛屿的面积,最终找到最大的岛屿面积。
562

被折叠的 条评论
为什么被折叠?



