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
def solve ( A , N , M ) : NEW_LINE INDENT B = [ ] NEW_LINE c = 1 NEW_LINE s = set ( ) NEW_LINE for i in range ( N ) : NEW_LINE INDENT new = [ ] NEW_LINE for j in range ( M ) : NEW_LINE INDENT new . append ( c ) NEW_LINE c = c + 1 NEW_LINE DEDENT B . append ( new ) NEW_LINE DEDENT for i in range ( N ) : NEW_LINE INDENT for j in range ( M ) : NEW_LINE INDENT if i != 0 : NEW_LINE INDENT if A [ i - 1 ] [ j ] == A [ i ] [ j ] : NEW_LINE INDENT B [ i - 1 ] [ j ] = B [ i ] [ j ] NEW_LINE DEDENT DEDENT if ( i != N - 1 ) : NEW_LINE INDENT if A [ i + 1 ] [ j ] == A [ i ] [ j ] : NEW_LINE INDENT B [ i + 1 ] [ j ] = B [ i ] [ j ] NEW_LINE DEDENT DEDENT if ( j != 0 ) : NEW_LINE INDENT if A [ i ] [ j - 1 ] == A [ i ] [ j ] : NEW_LINE INDENT B [ i ] [ j - 1 ] = B [ i ] [ j ] NEW_LINE DEDENT DEDENT if ( j != M - 1 ) : NEW_LINE INDENT if ( A [ i ] [ j + 1 ] == A [ i ] [ j ] ) : NEW_LINE INDENT B [ i ] [ j + 1 ] = B [ i ] [ j ] NEW_LINE DEDENT DEDENT DEDENT DEDENT for i in range ( N ) : NEW_LINE INDENT for j in range ( M ) : NEW_LINE INDENT s . add ( B [ i ] [ j ] ) NEW_LINE DEDENT DEDENT return len ( s ) NEW_LINE DEDENT N = 2 NEW_LINE M = 3 NEW_LINE A = [ [ 2 , 1 , 3 ] , [ 1 , 1 , 2 ] ] NEW_LINE print ( solve ( A , N , M ) ) NEW_LINE