Count of ways to select K consecutive empty cells from a given Matrix | C ++ 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; 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 * m + j ) == '1' ) { countcons = 0 ; } else { countcons ++ ; } if ( countcons >= k ) { ans ++ ; } } } return ans ; } 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 * n + i ) == '1' ) { countcons = 0 ; } else { countcons ++ ; } if ( countcons >= k ) { ans ++ ; } } } return ans ; } int main ( ) { int n = 3 , m = 3 , k = 1 ; char v [ n ] [ m ] = { '0' , '0' , '0' , '0' , '0' , '0' , '0' , '0' , '0' } ; if ( k == 1 ) { cout << rowWise ( v [ 0 ] , n , m , k ) ; } else { cout << colWise ( v [ 0 ] , n , m , k ) + rowWise ( v [ 0 ] , n , m , k ) ; } return 0 ; }