Min number of moves to traverse entire Matrix through connected cells with equal values | C # program to find the minimum number of moves to traverse a given matrix ; 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
using System ; using System . Collections . Generic ; class GFG { static int solve ( int [ , ] A , int N , int M ) { int [ , ] B = new int [ N , M ] ; int c = 1 ; HashSet < int > s = new HashSet < int > ( ) ; for ( int i = 0 ; i < N ; i ++ ) { for ( int j = 0 ; j < M ; j ++ ) B [ i , j ] = c ++ ; } for ( int i = 0 ; i < N ; i ++ ) { for ( int 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 ( int i = 0 ; i < N ; i ++ ) { for ( int j = 0 ; j < M ; j ++ ) s . Add ( B [ i , j ] ) ; } return s . Count ; } public static void Main ( String [ ] args ) { int N = 2 , M = 3 ; int [ , ] A = { { 2 , 1 , 3 } , { 1 , 1 , 2 } } ; Console . Write ( solve ( A , N , M ) ) ; } }