​LeetCode解法汇总面试题 16.19. 水域大小

 目录链接:

力扣编程题-解法汇总_分享+记录-CSDN博客

GitHub同步刷题项目:

https://github.com/September26/java-algorithms

原题链接:力扣


描述:

你有一个用于表示一片土地的整数矩阵land,该矩阵中每个点的值代表对应地点的海拔高度。若值为0则表示水域。由垂直、水平或对角连接的水域为池塘。池塘的大小是指相连接的水域的个数。编写一个方法来计算矩阵中所有池塘的大小,返回值需要从小到大排序。

示例:

输入:
[
  [0,2,1,0],
  [0,1,0,1],
  [1,1,0,1],
  [0,1,0,1]
]
输出: [1,2,4]

提示:

  • 0 < len(land) <= 1000
  • 0 < len(land[i]) <= 1000

解题思路:

* 解题思路:

* 因为担心递归遍历会导致堆栈溢出,所以采取的队列的方式。

* 遍历每个点,如果是海域则加入到queue中,并且记录size=1,然后取出queue中的头部,每个点都向周围8个方向探测,如果也为海域,则也加入到queue中,并且size+1;

* 最后把size加入到record中。

代码:

class Solution_MS_1619
{
public:
    static constexpr int directions[8][2] = {{1, 0}, {1, -1}, {0, -1}, {-1, -1}, {-1, 0}, {-1, 1}, {0, 1}, {1, 1}};

    vector<int> pondSizes(vector<vector<int>> &land)
    {
        vector<int> record;
        for (int y = 0; y < land.size(); y++)
        {
            for (int x = 0; x < land[0].size(); x++)
            {
                if (land[y][x] != 0)
                {
                    continue;
                }
                int size = 1;
                queue<pair<int, int>> qu;
                qu.push(make_pair(x, y));
                land[y][x] = 1;
                while (!qu.empty())
                {
                    pair<int, int> top = qu.front();
                    qu.pop();
                    for (int i = 0; i < 8; i++)
                    {
                        int nx = top.first + directions[i][0];
                        int ny = top.second + directions[i][1];
                        if (nx < 0 || ny < 0 || nx >= land[0].size() || ny >= land.size())
                        {
                            continue;
                        }
                        if (land[ny][nx] == 0)
                        {
                            size++;
                            land[ny][nx] = 1;
                            qu.push(make_pair(nx, ny));
                        }
                    }
                }
                record.push_back(size);
            }
        }
        sort(record.begin(), record.end());
        return record;
    }
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

失落夏天

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值