If current element is different from the previous element i . e . it is appearing for the first time in the current row
if ( mat [ i , j ] != mat [ i , j - 1 ] ) if ( cnt . ContainsKey ( mat [ i , j ] ) ) { cnt [ mat [ i , j ] ] = cnt [ mat [ i , j ] ] + 1 ; } else { cnt . Add ( mat [ i , j ] , 1 ) ; } } }