Minimum number of points required to cover all blocks of a 2-D grid
Last Updated :
11 May, 2022
Given two integers N and M. The task is to find the minimum number of points required to cover an N * M grid.
A point can cover two blocks in a 2-D grid when placed in any common line or sideline.
Examples:
Input: N = 5, M = 7
Output: 18
Input: N = 3, M = 8
Output: 12
Approach: This problem can be solved using Greedy Approach. The main idea is to observe that a single point placed on the common line or sideline covers two blocks. So the total number of points needed to cover all the blocks(say B blocks) is B/2 when B is even else B/2 + 1 when B is odd.
For a grid having N*M blocks, The total number of blocks will be (N*M)/2 when either one of them is even. Otherwise, it will require ((N*M)/2) + 1 points to cover all the blocks and one extra for last untouched block.
Below is the image to show how points can be used to cover block in a 2D-grid:
Point ‘A’ covers two blocks and ‘B’ covers one block.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int minPoints( int n, int m)
{
int ans = 0;
if ((n % 2 != 0)
&& (m % 2 != 0)) {
ans = ((n * m) / 2) + 1;
}
else {
ans = (n * m) / 2;
}
return ans;
}
int main()
{
int N = 5, M = 7;
cout << minPoints(N, M);
return 0;
}
|
Java
class GFG{
static int minPoints( int n, int m)
{
int ans = 0 ;
if ((n % 2 != 0 ) && (m % 2 != 0 ))
{
ans = ((n * m) / 2 ) + 1 ;
}
else
{
ans = (n * m) / 2 ;
}
return ans;
}
public static void main (String[] args)
{
int N = 5 , M = 7 ;
System.out.print(minPoints(N, M));
}
}
|
Python3
def minPoints(n, m):
ans = 0
if ((n % 2 ! = 0 ) and (m % 2 ! = 0 )):
ans = ((n * m) / / 2 ) + 1
else :
ans = (n * m) / / 2
return ans
if __name__ = = '__main__' :
N = 5
M = 7
print (minPoints(N, M))
|
C#
using System;
class GFG{
static int minPoints( int n, int m)
{
int ans = 0;
if ((n % 2 != 0) && (m % 2 != 0))
{
ans = ((n * m) / 2) + 1;
}
else
{
ans = (n * m) / 2;
}
return ans;
}
public static void Main(String[] args)
{
int N = 5, M = 7;
Console.Write(minPoints(N, M));
}
}
|
Javascript
<script>
function minPolets(n, m)
{
let ans = 0;
if ((n % 2 != 0) && (m % 2 != 0))
{
ans = Math.floor((n * m) / 2) + 1;
}
else
{
ans = Math.floor((n * m) / 2);
}
return ans;
}
let N = 5, M = 7;
document.write(minPolets(N, M));
</script>
|
Time Complexity: O(1)
Auxiliary Space: O(1)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...