Count of ways to select K consecutive empty cells from a given Matrix | Java program to find no of ways to select K consecutive empty cells from a row or column ; Function to Traverse the matrix row wise ; Initialize ans ; Traverse row wise ; Initialize no of consecutive empty cells ; Check if blocked cell is encountered then reset countcons to 0 ; Check if empty cell is encountered , then increment countcons ; Check if number of empty consecutive cells is greater or equal to K , increment the ans ; Return the count ; Function to Traverse the matrix column wise ; Initialize ans ; Traverse column wise ; Initialize no of consecutive empty cells ; Check if blocked cell is encountered then reset countcons to 0 ; Check if empty cell is encountered , increment countcons ; Check if number of empty consecutive cells is greater than or equal to K , increment the ans ; Return the count ; Driver Code ; If k = 1 only traverse row wise ; Traverse both row and column wise
import java . util . * ; class GFG { static int rowWise ( char [ ] [ ] v , int n , int m , int k ) { int ans = 0 ; for ( int i = 0 ; i < n ; i ++ ) { int countcons = 0 ; for ( int j = 0 ; j < m ; j ++ ) { if ( v [ i ] [ j ] == '1' ) { countcons = 0 ; } else { countcons ++ ; } if ( countcons >= k ) { ans ++ ; } } } return ans ; } static int colWise ( char [ ] [ ] v , int n , int m , int k ) { int ans = 0 ; for ( int i = 0 ; i < m ; i ++ ) { int countcons = 0 ; for ( int j = 0 ; j < n ; j ++ ) { if ( v [ j ] [ i ] == '1' ) { countcons = 0 ; } else { countcons ++ ; } if ( countcons >= k ) { ans ++ ; } } } return ans ; } public static void main ( String [ ] args ) { int n = 3 , m = 3 , k = 1 ; char v [ ] [ ] = { { '0' , '0' , '0' } , { '0' , '0' , '0' } , { '0' , '0' , '0' } } ; if ( k == 1 ) { System . out . print ( rowWise ( v , n , m , k ) ) ; } else { System . out . print ( colWise ( v , n , m , k ) + rowWise ( v , n , m , k ) ) ; } } }