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