|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
题目描述:
- 在给定的二维二进制数组 A 中,存在两座岛。(岛是由四面相连的 1 形成的一个最大组。)
- 现在,我们可以将 0 变为 1,以使两座岛连接起来,变成一座岛。
- 返回必须翻转的 0 的最小数目。(可以保证答案至少是 1。)
-
- 示例 1:
- 输入:[[0,1],[1,0]]
- 输出:1
- 示例 2:
- 输入:[[0,1,0],[0,0,0],[0,0,1]]
- 输出:2
- 示例 3:
- 输入:[[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]]
- 输出:1
-
- 提示:
- 1 <= A.length = A[0].length <= 100
- A[i][j] == 0 或 A[i][j] == 1
-
复制代码
- class Solution {
- private:
- vector<vector<int> > direct = {{-1, 0}, {0, -1}, {0, 1}, {1, 0}};
- public:
- void dfs(vector<vector<int> >& A, int i, int j){
- if(i < 0 || j < 0 || i >= A.size() || j >= A[0].size() || A[i][j] == 0 || A[i][j] == 2)return;
- A[i][j] = 2;
- for(auto cha : direct){
- dfs(A, i + cha[0], j + cha[1]);
- }
- }
- int bfs(vector<vector<int> >& A, vector<vector<int> >& index){
- queue<vector<int>> store;
- for(auto cha : index){
- store.push({cha[0], cha[1]});
- }
- int res = 0;
- int len1 = A.size(), len2 = A[0].size();
- bool flag = false;
- while(!store.empty()){
- vector<vector<int> > temp;
- while(!store.empty()){
- temp.push_back(store.front());
- store.pop();
- }
- for(auto index : temp){
- for(auto cha : direct){
- int temp1 = index[0] + cha[0], temp2 = index[1] + cha[1];
- if(temp1 < 0 || temp1 >= len1 || temp2 < 0 || temp2 >= len2)continue;
- if(A[temp1][temp2] == 2)return res;
- if(A[temp1][temp2] == 0){
- flag = true;
- store.push({temp1, temp2});
- A[temp1][temp2] = 3;
- }
- }
- }
- res++;
- }
- return INT_MAX;
- }
- int shortestBridge(vector<vector<int>>& A) {
- //先标记一个岛,将其全部变为2;
- int len1 = A.size(), len2 = A[0].size();
- int temp1, temp2;
- for(int i = 0; i < len1; i++){
- for(int j = 0; j < len2; j++){
- if(A[i][j] == 1){
- temp1 = i, temp2 = j;
- break;
- }
- }
- }
- dfs(A, temp1, temp2);
- vector<vector<int> >temp;
- for(int i = 0 ; i < len1; i++){
- for(int j = 0; j < len2; j++){
- if(A[i][j] == 1){
- temp.push_back({i, j});
- }
- }
- }
- return bfs(A, temp);
- }
- };
复制代码 |
|