LeetCode 0934. 最短的桥

60 阅读1分钟

持续创作,加速成长!这是我参与「掘金日新计划 · 10 月更文挑战」的第25天,点击查看活动详情

方法一:广搜

在熟练掌握了图的搜索后,这道题也不难,两次搜索就可以了。

第一次搜索的时候,我们从任意一个“1”开始,当四联通(上下左右)还是1时,继续搜索,直到把一个“岛”搜完。

这样,我们就得到了一个完整的“岛”

第二次搜索的时候,我们从第一次得到的“岛”开始,一圈一圈地往外拓展。每走一步,答案加一。直到遇到新的“岛”为止

  • 时间复杂度O(n2)O(n^2),一共进行了两次搜索
  • 空间复杂度O(n2)O(n^2),空间复杂度主要来自队列

AC代码

C++

typedef pair<int, int> pii;
const static int directions[4][2] = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
class Solution {
private:
    // vector<vector<int>> distance;
    int n;

    queue<pii> getIslandBy1Node(int x, int y, vector<vector<int>>& grid) {
        grid[x][y] = -1;
        queue<pii> q, ans;
        q.push({x, y});
        ans.push({x, y});
        while (q.size()) {
            pii thisNode = q.front();
            q.pop();
            for (int d = 0; d < 4; d++) {
                int tx = thisNode.first + directions[d][0];
                int ty = thisNode.second + directions[d][1];
                if (tx >= 0 && tx < n && ty >= 0 && ty < n) {
                    if (grid[tx][ty] == 1) {
                        grid[tx][ty] = -1;
                        q.push({tx, ty});
                        ans.push({tx, ty});
                    }
                }
            }
        }
        return ans;
    }
public:
    int shortestBridge(vector<vector<int>>& grid) {
        n = grid.size();
        // distance = vector<vector<int>>(n, vector<int>(n));
        queue<pii> q;
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                if (grid[i][j]) {
                    q = getIslandBy1Node(i, j, grid);
                    goto loop;
                }
            }
        }
        loop:;
        int ans = 0;
        while (true) {
            for (int i = q.size(); i > 0; i--) {
                pii thisNode = q.front();
                q.pop();
                for (int d = 0; d < 4; d++) {
                    int tx = thisNode.first + directions[d][0];
                    int ty = thisNode.second + directions[d][1];
                    if (tx >= 0 && tx < n && ty >= 0 && ty < n) {
                        if (grid[tx][ty] == 1) {
                            return ans;
                        }
                        if (grid[tx][ty] == 0) {
                            grid[tx][ty] = -1;
                            q.push({tx, ty});
                        }
                    }
                }
            }
            ans++;
        }
        // return -1;  // FakeReturn
    }
};

同步发文于CSDN,原创不易,转载请附上原文链接哦~ Tisfy:letmefly.blog.csdn.net/article/det…