LeetCode每天刷day35:Max Area of Island

版权声明:本文为博主原创文章,未经博主允许可以转载。(转呀转呀/笑哭),希望标注出处hhh https://blog.csdn.net/qq_36428171/article/details/89420491

题目:
给定一个包含了一些 0 和 1的非空二维数组 grid , 一个 岛屿 是由四个方向 (水平或垂直) 的 1 (代表土地) 构成的组合。你可以假设二维矩阵的四个边缘都被水包围着。

找到给定的二维数组中最大的岛屿面积。(如果没有岛屿,则返回面积为0。)

题目链接:Max Area of Island
C++:

class Solution {
public:
	int maxAreaOfIsland(vector<vector<int>>& g) {
		int areas = 0, maxAreas = 0;
		for (int i = 0; i < g.size(); i++)
		{
			for (int j = 0; j < g[0].size(); j++)
			{
				if (g[i][j] == 1)
				{
					areas = dfs(g, i, j);
					if (areas > maxAreas)
						maxAreas = areas;
				}

			}
		}
		return maxAreas;
	}
	int dfs(vector<vector<int> > &g, int x, int y)
	{
		if (x >= g.size() || y >= g[0].size() || x < 0 || y < 0 || g[x][y] != 1)
			return 0;
		else
		{
			g[x][y] = -1;
			return dfs(g, x - 1, y) + dfs(g, x + 1, y) + dfs(g, x, y + 1) + dfs(g, x, y - 1) + 1;
		}
	}
};

猜你喜欢

转载自blog.csdn.net/qq_36428171/article/details/89420491