Minimum number of points required to cover all blocks of a 2-D grid
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.
Input: N = 5, M = 7
Input: N = 3, M = 8
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:
Time Complexity: O(1)
Auxiliary Space: O(1)
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.