leetcode 695. Max Area of Island 岛屿的最大面积 + 十分典型的深度优先遍历DFS
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即可,
代码如下:
#include <iostream>
#include <vector>
#include <map>
#include <set>
#include <queue>
#include <stack>
#include <string>
#include <climits>
#include <algorithm>
#include <sstream>
#include <functional>
#include <bitset>
#include <numeric>
#include <cmath>
#include <regex>
using namespace std;
class Solution
{
public:
int res = 0;
int maxAreaOfIsland(vector<vector<int>>& grid)
{
int row = grid.size(), col = grid[0].size();
vector<vector<bool>> visit(row, vector<bool>(col, false));
for (int i = 0; i < row; i++)
{
for (int j = 0; j < col; j++)
{
if (grid[i][j] == 1)
{
int cur = 0;
dfs(grid, visit, i, j, cur);
}
}
}
return res;
}
void dfs(vector<vector<int>>& a, vector<vector<bool>>& visit, int x, int y, int& cur)
{
int row = a.size(), col = a[0].size();
if (x < 0 || x >= row || y < 0 || y >= col || a[x][y] == 0 || visit[x][y] == true)
return;
else
{
visit[x][y] = true;
cur+=1;
res = max(res, cur);
vector<vector<int>> dirs{ { 0,-1 },{ -1,0 },{ 0,1 },{ 1,0 } };
for (auto dir : dirs)
dfs(a, visit, x + dir[0], y + dir[1], cur);
}
}
};
还没有评论,来说两句吧...