LeetCode广度优先搜索BFS-695岛屿的最大面积

题目描述:

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

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

示例 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。

注意: 给定的矩阵grid 的长度和宽度都不超过 50。

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

 

思路:

直接BFS即可。

 

参考代码:

typedef struct Loc {
	int x;
	int y;
};

int BFS(Loc loc,vector<vector<int>>& grid) {
	int ans = 1;
	int dx[4] = { 0, 0, -1, 1 };
	int dy[4] = { 1, -1, 0, 0 };
	queue<Loc> que;
	que.push(loc);
	grid[loc.y][loc.x] = 0;
	while (!que.empty()){
		Loc tmp = que.front();
		que.pop();
		for (int i = 0; i < 4; i++) {
			if ((tmp.y + dy[i]) >= 0 && (tmp.y + dy[i]) < grid.size() &&
				(tmp.x + dx[i]) >= 0 && (tmp.x + dx[i]) < grid[0].size() &&
				grid[tmp.y + dy[i]][tmp.x + dx[i]] == 1) {
				Loc newLoc;
				newLoc.x = tmp.x + dx[i];
				newLoc.y = tmp.y + dy[i];
				que.push(newLoc);
				ans += 1;
				grid[newLoc.y][newLoc.x] = 0;
			}
		}
	}
	return ans;
}

int maxAreaOfIsland(vector<vector<int>>& grid) {
	int ans = 0;
	for (int i = 0; i < grid.size(); i++) {
		for (int j = 0; j < grid[i].size(); j++) {
			if (grid[i][j] == 1) {
				Loc loc;
				loc.x = j;
				loc.y = i;
				int tmp = BFS(loc, grid);
				if (tmp > ans)
					ans = tmp;
			}
		}
	}

	return ans;
}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值