Min number of moves to traverse entire Matrix through connected cells with equal values | Java 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
import java . util . * ; class GFG { static int solve ( int A [ ] [ ] , int N , int M ) { int [ ] [ ] B = new int [ N ] [ M ] ; int c = 1 ; HashSet < Integer > s = new HashSet < Integer > ( ) ; 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 . size ( ) ; } public static void main ( String [ ] args ) { int N = 2 , M = 3 ; int A [ ] [ ] = { { 2 , 1 , 3 } , { 1 , 1 , 2 } } ; System . out . print ( solve ( A , N , M ) ) ; } }