Iterating over the matrix
for ( int i = 0 ; i < N ; i ++ ) { for ( int j = 0 ; j < M ; j ++ ) { if ( i + j == left ) { if ( mp . ContainsKey ( mat [ i , j ] ) ) { mp [ mat [ i , j ] ] ++ ; } else { mp [ mat [ i , j ] ] = 1 ; } totalsize ++ ; } else if ( i + j == right ) { if ( mp . ContainsKey ( mat [ i , j ] ) ) { mp [ mat [ i , j ] ] ++ ; } else { mp [ mat [ i , j ] ] = 1 ; } totalsize ++ ; } } }