📜  使两个岛屿在网格中连接的最小水陆转换次数

📅  最后修改于: 2021-09-08 12:43:45             🧑  作者: Mango

给定 ‘W’‘L’的二维网格arr[][] ,其中‘W’表示水, ‘L’表示陆地,任务是找到必须更改为陆地的水分量 ‘W’ 的最小数量组件“L”,使两个岛连接起来。

注意:只能有两个不相交的岛。

例子:

方法:这个问题可以使用 Floodfill 算法解决。以下是步骤:

  1. 对第一组连接的岛屿使用 Floodfill 算法,并使所有岛屿都被访问并将坐标存储在哈希中(比如hash1 )。
  2. 对第二组连接的岛屿使用 Floodfill 算法,并使所有岛屿都被访问,并将坐标存储在第二个哈希中(比如hash2 )。
  3. 存储在散列中的坐标之间的最小差异就是所需的结果。

下面是上述方法的实现:

C++
// C++ program for the above approach
 
#include 
using namespace std;
 
// Determine the distance between two
// coordinates
int dist(pair& p1,
         pair& p2)
{
 
    return abs(p1.first - p2.first)
           + abs(p2.second - p1.second) - 1;
}
 
// Function to implement floodfill algorithm
void floodfill(set >& hash,
               int i, int j,
               vector >& A)
{
 
    // Base Case
    if (i < 0 || i >= A.size() || j < 0
        || j >= A[0].size() || A[i][j] != 'L') {
        return;
    }
 
    // Mark the current node visited
    A[i][j] = 'V';
 
    // Store the coordinates of in the
    // hash set
    hash.insert(make_pair(i, j));
 
    // Recursively iterate for the next
    // four directions
    floodfill(hash, i - 1, j, A);
    floodfill(hash, i + 1, j, A);
    floodfill(hash, i, j - 1, A);
    floodfill(hash, i, j + 1, A);
}
 
// Funtion to find the minimum 'W' to flipped
void findMinimumW(vector >& A)
{
 
    // Base Case
    if (A.size() == 0)
        return;
 
    // Two sets to store the coordinates of
    // connected island
    set > hash1, hash2;
 
    // Traversing the given grid[][]
    for (int i = 0; i < A.size(); i++) {
 
        for (int j = 0; j < A[0].size(); j++) {
 
            // If an island is found
            if (A[i][j] == 'L') {
 
                // Floodfill Algorithm for
                // the first island
                if (hash1.empty()) {
                    floodfill(hash1, i, j, A);
                }
 
                // Floodfill Algorithm for
                // the second island
                if (hash2.empty()
                    && !hash1.count({ i, j })) {
                    floodfill(hash2, i, j, A);
                }
            }
        }
    }
 
    // To store the minimum count of 'W'
    int ans = INT_MAX;
 
    // Traverse both pairs of hashes
    for (auto i : hash1) {
        for (auto j : hash2) {
            ans = min(ans, dist(i, j));
        }
    }
 
    // Print the final answer
    cout << ans << endl;
}
 
// Driver Code
int main()
{
 
    // Given grid of land and water
    vector > arr;
    arr = { { 'W', 'L' }, { 'L', 'W' } };
 
    // Function Call
    findMinimumW(arr);
    return 0;
}


Python3
# Python3 program for the above approach
import sys
 
# Determine the distance between two
# coordinates
def dist(p1, p2):
     
    return (abs(p1[0] - p2[0]) +
            abs(p2[1] - p1[1]) - 1)
 
# Function to implement floodfill algorithm
def floodfill(hash, i, j, A):
     
    # Base Case
    if (i < 0 or i >= len(A) or j < 0 or
        j >= len(A[0]) or A[i][j] != 'L'):
        return hash, A
         
    # Mark the current node visited
    A[i][j] = 'V'
  
    # Store the coordinates of in the
    # hash set
    hash.add((i, j))
     
    # Recursively iterate for the next
    # four directions
    hash, A = floodfill(hash, i - 1, j, A)
    hash, A = floodfill(hash, i + 1, j, A)
    hash, A = floodfill(hash, i, j - 1, A)
    hash, A = floodfill(hash, i, j + 1, A)
    return hash, A
 
# Funtion to find the minimum 'W' to flipped
def findMinimumW(A):
     
    # Base Case
    if (len(A) == 0):
        return set(), A
         
    # Two sets to store the coordinates of
    # connected island
    hash1 = set()
    hash2 = set()
     
    # Traversing the given grid[][]
    for i in range(len(A)):
        for j in range(len(A[0])):
             
            # If an island is found
            if (A[i][j] == 'L'):
                 
                # Floodfill Algorithm for
                # the first island
                if (len(hash1) == 0):
                    hash1, A = floodfill(hash1, i, j, A)
                     
                # Floodfill Algorithm for
                # the second island
                if (len(hash2) == 0 and
                   (i, j) not in hash1):
                    hash2, A = floodfill(hash2, i, j, A)
                     
    # To store the minimum count of 'W'
    ans = sys.maxsize
  
    # Traverse both pairs of hashes
    for i in hash1:
        for j in hash2:
            ans = min(ans, dist(i, j))
             
    # Print the final answer
    print(ans)
     
# Driver Code
if __name__=='__main__':
  
    # Given grid of land and water
    arr = []
    arr = [ [ 'W', 'L' ], [ 'L', 'W' ] ]
  
    # Function Call
    findMinimumW(arr)
 
# This code is contributed by pratham76


输出:
1

时间复杂度: O(N 2 )

如果您想与行业专家一起参加直播课程,请参阅Geeks Classes Live