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

📅  最后修改于: 2021-10-26 06:35:30             🧑  作者: 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


Javascript


输出:
18

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

如果您希望与专家一起参加现场课程,请参阅DSA 现场工作专业课程学生竞争性编程现场课程