Count 1 s in binary matrix having remaining indices of its row and column filled with 0 s | Java program for the above approach ; Function to count required 1 s from the given matrix ; Stores the dimensions of the mat [ ] [ ] ; Calculate sum of rows ; Calculate sum of columns ; Stores required count of 1 s ; If current cell is 1 and sum of row and column is 1 ; Increment count of 1 s ; Return the final count ; Driver Code ; Given matrix ; Function call
class GFG { static int numSpecial ( int [ ] [ ] mat ) { int m = mat . length ; int n = mat [ 0 ] . length ; int [ ] rows = new int [ m ] ; int [ ] cols = new int [ n ] ; int i , j ; for ( i = 0 ; i < m ; i ++ ) { rows [ i ] = 0 ; for ( j = 0 ; j < n ; j ++ ) rows [ i ] += mat [ i ] [ j ] ; } for ( i = 0 ; i < n ; i ++ ) { cols [ i ] = 0 ; for ( j = 0 ; j < m ; j ++ ) cols [ i ] += mat [ j ] [ i ] ; } int cnt = 0 ; for ( i = 0 ; i < m ; i ++ ) { for ( j = 0 ; j < n ; j ++ ) { if ( mat [ i ] [ j ] == 1 && rows [ i ] == 1 && cols [ j ] == 1 ) cnt ++ ; } } return cnt ; } public static void main ( String [ ] args ) { int [ ] [ ] mat = { { 1 , 0 , 0 } , { 0 , 0 , 1 } , { 0 , 0 , 0 } } ; System . out . print ( numSpecial ( mat ) + "NEW_LINE"); } }