LeetCode #934. Shortest Bridge

题目描述:

In a given 2D binary array A, there are two islands.  (An island is a 4-directionally connected group of 1s not connected to any other 1s.)

Now, we may change 0s to 1s so as to connect the two islands together to form 1 island.

Return the smallest number of 0s that must be flipped.  (It is guaranteed that the answer is at least 1.)

Example 1:

Input: [[0,1],[1,0]]
Output: 1

Example 2:

Input: [[0,1,0],[0,0,0],[0,0,1]]
Output: 2

Example 3:

Input: [[1,1,1,1,1],[1,0,0,0,1],[1,0,1,0,1],[1,0,0,0,1],[1,1,1,1,1]]
Output: 1

Note:

  1. 1 <= A.length = A[0].length <= 100
  2. A[i][j] == 0 or A[i][j] == 1
class Solution {
public:
    int shortestBridge(vector<vector<int>>& A) {
        // 利用DFS将一个岛的所有点都加入队列中,这些点的起始距离都是零
        int m=A.size(), n=A[0].size();
        queue<pair<int,int>> q;
        unordered_map<int,int> dist;
        bool found=false; // 必须加上一个变量表示有没有找到一个岛
        for(int i=0;i<m&&!found;i++)
        {
            for(int j=0;j<n&&!found;j++)
            {
                if(A[i][j]==1) 
                {
                    DFS(A,i,j,q,dist);
                    found=true;
                }
            }
        }
        
        // 做BFS找最先遇到的另一个岛的点
        vector<pair<int,int>> dirs={{0,1},{0,-1},{1,0},{-1,0}};
        while(!q.empty())
        {
            int i=q.front().first, j=q.front().second;
            q.pop();
            for(pair<int,int> dir:dirs)
            {
                int x=i+dir.first, y=j+dir.second;
                if(x<0||x>=m||y<0||y>=n||dist.count(x*n+y)) continue;
                dist[x*n+y]=dist[i*n+j]+1;
                if(A[x][y]==1) return dist[x*n+y]-1; // 需要修改的节点数是距离减一
                q.push({x,y});
            }
        }
        return -1;
    }
    
    void DFS(vector<vector<int>>& A, int i, int j, queue<pair<int,int>>& q, unordered_map<int,int>& dist)
    {
        int m=A.size(), n=A[0].size();
        if(A[i][j]!=1||dist.count(i*n+j)) return;
        dist[i*n+j]=0;
        q.push({i,j});
        if(i>0) DFS(A,i-1,j,q,dist);
        if(i<n-1) DFS(A,i+1,j,q,dist);
        if(j>0) DFS(A,i,j-1,q,dist);
        if(j<m-1) DFS(A,i,j+1,q,dist);
    }
};

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值