Given N * M rectangular park having N rows and M columns, each cell of the park is a square of unit area and boundaries between the cells is called hex and a sprinkler can be placed in the middle of the hex. The task is to find the minimum number of sprinklers required to water the entire park.
Input: N = 3 M = 3
For the first two columns 3 sprinklers are required and for last column we are bound to use 2 sprinklers to water the last column.
Input: N = 5 M = 3
For the first two columns 5 sprinklers are required and for last column we are bound to use 3 sprinklers to water the last column.
- After making some observation one thing can be point out i.e for every two column, N sprinkler are required because we can placed them in between of two columns.
- If M is even, then clearly N* (M / 2) sprinklers are required.
- But if M is odd then solution for M – 1 column can be computed using even column formula, and for last column add ( N + 1) / 2 sprinkler to water the last column irrespective of N is odd or even.
Here is implementation of 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.