最大岛屿面积——续

最大岛屿面积

  • 栈+DFS实现
    上一篇是直接搜索(DFS),采用递归的思想,本篇是利用栈结构+DFS来实现。
    代码实现:(注释很详细)
#include<iostream>
#include<vector>
#include<stack>
#include<algorithm>
using namespace std;


//栈+DFS实现
class Solution {
public:
	int direction[5] = { 0,-1,0,1,0 };	//方向数组:上、左、下、右
	int maxAreaOfIsland(vector<vector<int>>& grid) {
		const int m = grid.size(), n = grid[0].size();	//m*n
		int area = 0;			//岛屿面积
		stack<int> stack_i;		//存x轴坐标
		stack<int> stack_j;		//存y轴坐标
		for (int i = 0; i < m; i++) {	//遍历每个岛屿
			for (int j = 0; j < n; j++) {
				int res = 0;
				stack_i.push(i);
				stack_j.push(j);
				while (!stack_i.empty()) {
					int a = stack_i.top(), b = stack_j.top();	//获取栈顶元素
					stack_i.pop(), stack_j.pop();	//出栈
					for (int index = 0; index < 4; index++) {	//遍历这个点的四个方向
						int next_i = a + direction[index];
						int next_j = b + direction[index+1];
						if (next_i<0 || next_j<0 || next_i==m	\
							|| next_j==n || grid[next_i][next_j] != 1) continue;	//越界或值不为一则退出本次循环,进行下一次循环,直至遍历所有
						res += 1;	//记录每次面积的值
						grid[next_i][next_j] = 0;	//遍历这个点之后就置0
						stack_i.push(next_i);	//将这个点压栈,再去从这个点遍历
						stack_j.push(next_j);
					}
				}
				area = max(area, res);	//对比保留最大岛屿面积值
			}
		}
		
		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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值