Min number of moves to traverse entire Matrix through connected cells with equal values | Function to find the minimum number of moves to traverse the given matrix ; Constructing another matrix consisting of distinct values ; Updating the array B by checking the values of A that if there are same values connected through an edge or not ; Check for boundary condition of the matrix ; If adjacent cells have same value ; Check for boundary condition of the matrix ; If adjacent cells have same value ; Check for boundary condition of the matrix ; If adjacent cells have same value ; Check for boundary condition of the matrix ; If adjacent cells have same value ; Store all distinct elements in a set ; Return answer ; Driver Code ; Function Call
function solve ( A , N , M ) { var B = Array . from ( Array ( N ) , ( ) => Array ( M ) ) ; var c = 1 ; var s = new Set ( ) ; for ( var i = 0 ; i < N ; i ++ ) { for ( var j = 0 ; j < M ; j ++ ) B [ i ] [ j ] = c ++ ; } for ( var i = 0 ; i < N ; i ++ ) { for ( var j = 0 ; j < M ; j ++ ) { if ( i != 0 ) { if ( A [ i - 1 ] [ j ] == A [ i ] [ j ] ) B [ i - 1 ] [ j ] = B [ i ] [ j ] ; } if ( i != N - 1 ) { if ( A [ i + 1 ] [ j ] == A [ i ] [ j ] ) B [ i + 1 ] [ j ] = B [ i ] [ j ] ; } if ( j != 0 ) { if ( A [ i ] [ j - 1 ] == A [ i ] [ j ] ) B [ i ] [ j - 1 ] = B [ i ] [ j ] ; } if ( j != M - 1 ) { if ( A [ i ] [ j + 1 ] == A [ i ] [ j ] ) B [ i ] [ j + 1 ] = B [ i ] [ j ] ; } } } for ( var i = 0 ; i < N ; i ++ ) { for ( var j = 0 ; j < M ; j ++ ) s . add ( B [ i ] [ j ] ) ; } return s . size ; } var N = 2 , M = 3 ; var A = [ [ 2 , 1 , 3 ] , [ 1 , 1 , 2 ] ] ; document . write ( solve ( A , N , M ) ) ;