给你一个大小为 n x n 的二元矩阵 grid ,其中 1 表示陆地,0 表示水域。岛 是由四面相连的 1 形成的一个最大组,即不会与非组内的任何其他 1 相连。grid 中 恰好存在两座岛 。

class Solution {

public:

    int shortestBridge(vector<vector<int>>& grid) {

        int n = grid.size();

        vector<vector<int>> dirs = {{-1, 0}, {1, 0}, {0, 1}, {0, -1}};

        vector<pair<int, int>> island;

        queue<pair<int, int>> qu;

        for (int i = 0; i < n; i++) {

            for (int j = 0; j < n; j++) {

                if (grid[i][j] == 1) {

                    qu.emplace(i, j);

                    grid[i][j] = -1;

                    while (!qu.empty()) {

                        auto [x, y] = qu.front();

                        qu.pop();

                        island.emplace_back(x, y);

                        for (int k = 0; k < 4; k++) {

                            int nx = x + dirs[k][0];

                            int ny = y + dirs[k][1];

                            if (nx >= 0 && ny >= 0 && nx < n && ny < n && grid[nx][ny] == 1) {

                                qu.emplace(nx, ny);

                                grid[nx][ny] = -1;

                            }

                        }

                    }

                    for (auto &&[x, y] : island) {

                        qu.emplace(x, y);

                    }

                    int step = 0;

                    while (!qu.empty()) {

                        int sz = qu.size();

                        for (int i = 0; i < sz; i++) {

                            auto [x, y] = qu.front();

                            qu.pop();

                            for (int k = 0; k < 4; k++) {

                                int nx = x + dirs[k][0];

                                int ny = y + dirs[k][1];

                                if (nx >= 0 && ny >= 0 && nx < n && ny < n) {

                                    if (grid[nx][ny] == 0) {

                                        qu.emplace(nx, ny);

                                        grid[nx][ny] = -1;

                                    } else if (grid[nx][ny] == 1) {

                                        return step;

                                    }

                                }

                            }

                        }

                        step++;

                    }

                }

            }

        }

        return 0;

    }

};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值