695. 岛屿的最大面积

cpp 复制代码
class Solution {
public:
    int dir[4][2]={1,0,0,1,-1,0,0,-1};
    int ans=0;
    void bfs(vector<vector<bool> >&flag,int x,int y,vector<vector<int>>& grid){
        queue<pair<int,int> >q;
        q.push({x,y});
        flag[x][y]=true;
        int cnt=0;
        cnt++;
        while(!q.empty()){
            pair<int,int>p=q.front();
            q.pop();
            int nx=p.first;
            int ny=p.second;
            for(int i=0;i<4;i++){
                int xx=nx+dir[i][0];
                int yy=ny+dir[i][1];
                if(xx<0||yy<0||xx>=grid.size()||yy>=grid[0].size())continue;
                if(flag[xx][yy]==false&&grid[xx][yy]==1){
                    q.push({xx,yy});
                    flag[xx][yy]=true;
                    cnt++;
                }
            }
        }
        if(cnt>ans)ans=cnt;
    }
    int maxAreaOfIsland(vector<vector<int>>& grid) {
        int n=grid.size();
        int m=grid[0].size();
        vector<vector<bool> >flag=vector<vector<bool> >(n,vector<bool>(m,false));
        for(int i=0;i<n;i++){
            for(int j=0;j<m;j++){
                if(grid[i][j]==1&&flag[i][j]==false){
                    bfs(flag,i,j,grid);
                }
            }
        }
        return ans;
    }
};
相关推荐
XiYang-DING5 分钟前
【Java】二叉树
java·开发语言·数据结构
坚持编程的菜鸟5 分钟前
The Blocks Problem
数据结构·c++·算法
2301_822703206 分钟前
Flutter 框架跨平台鸿蒙开发 - 家庭时间胶囊应用
算法·flutter·华为·图形渲染·harmonyos·鸿蒙
tankeven6 分钟前
HJ171 排座椅
c++·算法
2301_8227032013 分钟前
成语小词典:鸿蒙Flutter实现的成语查询与管理应用
算法·flutter·华为·开源·图形渲染·harmonyos
Bczheng114 分钟前
八.账号生成规则 哈希 密钥
算法·哈希算法
黎阳之光15 分钟前
视频孪生领航者,以中国技术定义全球数智化新高度
大数据·人工智能·算法·安全·数字孪生
6Hzlia16 分钟前
【Hot 100 刷题计划】 LeetCode 39. 组合总和 | C++ 回溯算法与 startIndex 剪枝
c++·算法·leetcode
患得患失94927 分钟前
【前端WebSocket】心跳功能,心跳重置策略、双向确认(Ping-Pong) 以及 指数退避算法(Exponential Backoff)
前端·websocket·算法
海砥装备HardAus30 分钟前
飞控算法中双环串级PID深度解析:角度环与角速度环的协同机制
stm32·算法·无人机·飞控·串级pid