📜  覆盖二维网格的所有块所需的最少点数

📅  最后修改于: 2021-04-26 10:55:36             🧑  作者: Mango

给定两个整数NM。任务是找到覆盖N * M网格所需的最小点数。

例子:

方法:此问题可以使用贪婪方法解决。主要思想是观察放置在公共线或边线上的单个点覆盖了两个块。因此,当B为偶数时,覆盖所有块(例如B块)所需的总点数为B / 2 ,否则,当B为奇数时, B / 2 +1
对于具有N * M个块的网格,当其中一个为偶数时,块总数将为(N * M)/ 2 。否则,将需要((N * M)/ 2)+ 1分才能覆盖所有方块,而最后一个未触及的方块则需要额外一点。
下图显示了如何使用点覆盖2D网格中的块:

点“ A”覆盖两个块,而“ B”点覆盖一个块。
下面是上述方法的实现:

C++
// C++ program for the above approach
#include 
using namespace std;
 
// Function to find the minimum number
// of Points required to cover a grid
int minPoints(int n, int m)
{
    int ans = 0;
 
    // If number of block is even
    if ((n % 2 != 0)
        && (m % 2 != 0)) {
        ans = ((n * m) / 2) + 1;
    }
    else {
        ans = (n * m) / 2;
    }
 
    // Return the minimum points
    return ans;
}
 
// Driver Code
int main()
{
    // Given size of grid
    int N = 5, M = 7;
 
    // Function Call
    cout << minPoints(N, M);
    return 0;
}


Java
// Java program for the above approach
class GFG{
     
// Function to find the minimum number
// of Points required to cover a grid
static int minPoints(int n, int m)
{
    int ans = 0;
 
    // If number of block is even
    if ((n % 2 != 0) && (m % 2 != 0))
    {
        ans = ((n * m) / 2) + 1;
    }
    else
    {
        ans = (n * m) / 2;
    }
 
    // Return the minimum points
    return ans;
}
 
// Driver Code
public static void main (String[] args)
{
    // Given size of grid
    int N = 5, M = 7;
 
    // Function Call
    System.out.print(minPoints(N, M));
}
}
 
// This code is contributed by Ritik Bansal


Python3
# Python3 program for the above approach
 
# Function to find the minimum number
# of Points required to cover a grid
def minPoints(n, m):
 
    ans = 0
 
    # If number of block is even
    if ((n % 2 != 0) and (m % 2 != 0)):
        ans = ((n * m) // 2) + 1
 
    else:
        ans = (n * m) // 2
 
    # Return the minimum points
    return ans
 
# Driver code
if __name__ == '__main__':
 
    # Given size of grid
    N = 5
    M = 7
 
    # Function call
    print(minPoints(N, M))
 
# This code is contributed by himanshu77


C#
// C# program for the above approach
using System;
class GFG{
     
// Function to find the minimum number
// of Points required to cover a grid
static int minPoints(int n, int m)
{
    int ans = 0;
 
    // If number of block is even
    if ((n % 2 != 0) && (m % 2 != 0))
    {
        ans = ((n * m) / 2) + 1;
    }
    else
    {
        ans = (n * m) / 2;
    }
 
    // Return the minimum points
    return ans;
}
 
// Driver Code
public static void Main(String[] args)
{
    // Given size of grid
    int N = 5, M = 7;
 
    // Function Call
    Console.Write(minPoints(N, M));
}
}
 
// This code is contributed by sapnasingh4991


输出:
18


时间复杂度: O(1)
辅助空间: O(1)