力扣第695题 岛屿的最大面积

力扣第695题 岛屿的最大面积

class Solution {
    public:
    int maxAreaOfIsland(vector<vector<int>>& grid)
     {
        queue<int> que_i;
        queue<int> que_j;
        int leni = grid.size(), lenj = grid[0].size();
        int res = 0, cur = 0;
        int di[4] = { 0, 0, 1, -1 }; // 上下左右四个方向
        int dj[4] = { 1, -1, 0, 0 };
        for (int i = 0; i < leni; i++)
        {
            for (int j = 0; j < lenj; j++)
            {
                que_i.push(i);
                que_j.push(j);
                cur = 0;
                while (!que_i.empty())
                {
                    int idxi = que_i.front(), idxj = que_j.front();
                    que_i.pop();
                    que_j.pop();
                    if (idxi < 0 || idxj < 0 || idxi >= leni || idxj >= lenj || grid[idxi][idxj] != 1)
                        continue;
                    cur++;
                    grid[idxi][idxj] = 0; // 把原先的值置0,防止重复遍历
                    for (int k = 0; k < 4; k++)
                    {
                        que_i.push(idxi + di[k]);
                        que_j.push(idxj + dj[k]);
                    }
                }
                res = max<int>(res, cur);
            }
        }
        return res;
    }
};

posted on 2020-03-18 23:51  woodjay  阅读(135)  评论(0编辑  收藏  举报

导航