Number of cells in a matrix that satisfy the given condition | Javascript implementation of the approach ; Function to return the number of cells in which mirror can be placed ; Update the row array where row [ i ] [ j ] will store whether the current row i contains all 1 s in the columns starting from j ; Update the column array where col [ i ] [ j ] will store whether the current column j contains all 1 s in the rows starting from i ; To store the required result ; For every cell except the last row and the last column ; If the current cell is not blocked and the light can travel from the next row and the next column then the current cell is valid ; For the last column ; For the last row , note that the last column is not taken into consideration as the bottom right element has already been considered in the last column previously ; Driver code
let N = 3 ; function numberOfCells ( mat ) { let row = new Array ( N ) ; let col = new Array ( N ) ; for ( let i = 0 ; i < N ; i ++ ) { row [ i ] = new Array ( N ) ; col [ i ] = new Array ( N ) ; for ( let j = 0 ; j < N ; j ++ ) { row [ i ] [ j ] = 0 ; col [ i ] [ j ] = 0 ; } } for ( let i = 0 ; i < N ; i ++ ) { for ( let j = N - 1 ; j >= 0 ; j -- ) { if ( mat [ i ] [ j ] == 1 ) { row [ i ] [ j ] = ( j + 1 < N ) ? row [ i ] [ j + 1 ] : true ; } else { row [ i ] [ j ] = false ; } } } for ( let j = 0 ; j < N ; j ++ ) { for ( let i = N - 1 ; i >= 0 ; i -- ) { if ( mat [ i ] [ j ] == 1 ) { col [ i ] [ j ] = ( i + 1 < N ) ? col [ i + 1 ] [ j ] : true ; } else { col [ i ] [ j ] = false ; } } } let cnt = 0 ; for ( let i = 0 ; i < N - 1 ; i ++ ) { for ( let j = 0 ; j < N - 1 ; j ++ ) { if ( row [ i ] [ j ] && col [ i ] [ j ] ) { cnt ++ ; } } } for ( let i = 0 ; i < N ; i ++ ) { if ( col [ i ] [ N - 1 ] ) cnt ++ ; } for ( let j = 0 ; j < N - 1 ; j ++ ) { if ( row [ N - 1 ] [ j ] ) cnt ++ ; } return cnt ; } let mat = [ [ 0 , 1 , 1 ] , [ 0 , 1 , 1 ] , [ 0 , 1 , 1 ] ] ; document . write ( numberOfCells ( mat ) ) ;