最大岛屿面积(DFS实现)
我采用的是广度优先搜索(DFS)
- 抓住DFS的关键思想,我总结为一个词:一搜到底。
- 总结为一句话:递归的思想。
本题题目如下:
代码实现如下:(注释很详细)
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
class Solution {
public:
int dfs(vector<vector<int>>& grid, int x,int y) {
if (x < 0 || y < 0 || x == grid.size() || y == grid[0].size() \
|| grid[x][y] != 1) { //判断是否越界,是否满足等于1,不是则跳出此次循环,从下一个点搜索
return 0;
}
int res = 1;
grid[x][y] = 0; //访问后就将方格的值置为0
int dir_x[4] = { -1,0,1,0 }; //上右下左,方向矩阵
int dir_y[4] = { 0,1,0,-1 };
for (int index = 0; index < 4; index++) {
int next_x = x + dir_x[index];
int next_y = y + dir_y[index];
res += dfs(grid, next_x, next_y); //面积值
}
return res;
}
int maxAreaOfIsland(vector<vector<int>>& grid) {
int area = 0; //The area of island
const int m = grid.size(), n = grid[0].size(); //m*n
for (int i = 0; i < m; i++) { //遍历每一个小方格
for (int j = 0; j < n; j++) {
area = max(area, dfs(grid,i,j));
}
}
return area;
}
};
int main(int argc,char* argv[]){
Solution s;
vector<vector<int>> grid = { //input of island
{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,1,0,0,0},
};
cout << s.maxAreaOfIsland(grid) << endl; //输出最大岛屿面积
return 0;
}