岛屿的最大面积-Dfs

/*给定一个包含了一些 0 和 1 的非空二维数组?grid 。

一个?岛屿?是由一些相邻的?1?(代表土地) 构成的组合,这里的「相邻」要求两个 1 必须在水平或者竖直方向上相邻。你可以假设?grid 的四个边缘都被 0(代表水)包围着。

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

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/max-area-of-island
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。*/
/*示例 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]]
对于上面这个给定矩阵应返回?6。注意答案不应该是 11 ,因为岛屿只能包含水平或垂直的四个方向的 1 。

示例 2:

[[0,0,0,0,0,0,0,0]]
对于上面这个给定的矩阵, 返回?0。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/max-area-of-island
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。*/

class Solution {
    
    
public:
	//统计每个岛的面积
	int count = 0;
	void Dfs(vector<vector<int>>& grid, int r, int c) {
    
    
		int row = grid.size();
		int col = grid[0].size();
		//越界返回
		if (!(r >= 0 && r < row && c >= 0 && c < col))
			return;
		//为水域返回
		if (grid[r][c] == 0) {
    
    
			return;
		}
		//统计面积
		++count;
		//统计后将其改为水域,防止重复统计
		grid[r][c] = 0;
		//上下左右
		Dfs(grid, r + 1, c);
		Dfs(grid, r - 1, c);
		Dfs(grid, r, c + 1);
		Dfs(grid, r, c - 1);
	}
	int maxAreaOfIsland(vector<vector<int>>& grid) {
    
    
		if (grid.empty())
			return 0;
		//保存最大岛面积
		int max = 0;
		int row = grid.size();
		int col = grid[0].size();
		for (int i = 0; i < row; ++i) {
    
    
			for (int j = 0; j < col; ++j) {
    
    
				if (grid[i][j] == 1) {
    
    
					//统计下一个岛之前,将面积置为0
					count = 0;
					Dfs(grid, i, j);
					//每统计一个岛面积后,与max比较,max始终存最大面积
					if (count > max) {
    
    
						max = count;
					}
				}
			}
		}
		return max;
	}
};

猜你喜欢

转载自blog.csdn.net/weixin_45295598/article/details/108911456
今日推荐