Count cells in a grid from which maximum number of cells can be reached by K vertical or horizontal jumps | Java program for the above approach ; Function to count the number of cells in the grid such that maximum cell is reachable with a jump of K ; Maximum reachable rows from the current row ; Stores the count of cell that are reachable from the current row ; Count of reachable rows ; Update the maximum value ; Add it to the count ; Maximum reachable columns from the current column ; Stores the count of cell that are reachable from the current column ; Count of rechable columns ; Update the maximum value ; Add it to the count ; Return the total count of cells ; Driver Code
class GFG { public static long countCells ( int n , int m , int s ) { int mx1 = - 1 ; int cont1 = 0 ; for ( int i = 0 ; i < s && i < n ; ++ i ) { int aux = ( n - ( i + 1 ) ) / s + 1 ; if ( aux > mx1 ) { mx1 = cont1 = aux ; } else if ( aux == mx1 ) cont1 += aux ; } int mx2 = - 1 ; int cont2 = 0 ; for ( int i = 0 ; i < s && i < m ; ++ i ) { int aux = ( m - ( i + 1 ) ) / s + 1 ; if ( aux > mx2 ) mx2 = cont2 = aux ; else if ( aux == mx2 ) cont2 += aux ; } return ( long ) ( cont1 * cont2 ) ; } public static void main ( String args [ ] ) { int N = 5 , M = 5 , K = 2 ; System . out . println ( countCells ( N , M , K ) ) ; } }