Coordinates of the last cell in a Matrix on which performing given operations exits from the Matrix | JAVA program for the above approach ; Function to check if the indices ( i , j ) are valid indices in a Matrix or not ; Cases for invalid cells ; Return true if valid ; Function to find indices of cells of a matrix from which traversal leads to out of the matrix ; Starting from cell ( 0 , 0 ) , traverse in right direction ; Stores direction changes ; Iterate until the current cell exceeds beyond the matrix ; Current index ; If the current cell is 1 ; Update arr [ i ] [ j ] = 0 ; Update indices according to the direction ; Otherwise ; Update indices according to the direction ; The exit cooridnates ; Driver Code ; Number of rows ; Number of columns ; Given matrix arr [ ] [ ]
import java . util . HashMap ; import java . util . Map ; class GFG { static boolean issafe ( int m , int n , int i , int j ) { if ( i < 0 ) return false ; if ( j < 0 ) return false ; if ( i >= m ) return false ; if ( j >= n ) return false ; return true ; } static int [ ] endpoints ( int [ ] [ ] arr , int m , int n ) { int i = 0 ; int j = 0 ; int current_i = 0 ; int current_j = 0 ; char current_d = ' r ' ; Map < Character , Character > rcd = new HashMap < > ( ) ; rcd . put ( ' l ' , ' u ' ) ; rcd . put ( ' u ' , ' r ' ) ; rcd . put ( ' r ' , ' d ' ) ; rcd . put ( ' d ' , ' l ' ) ; while ( issafe ( m , n , i , j ) ) { current_i = i ; current_j = j ; if ( arr [ i ] [ j ] == 1 ) { char move_in = rcd . get ( current_d ) ; arr [ i ] [ j ] = 0 ; if ( move_in == ' u ' ) i -= 1 ; else if ( move_in == ' d ' ) i += 1 ; else if ( move_in == ' l ' ) j -= 1 ; else if ( move_in == ' r ' ) j += 1 ; current_d = move_in ; } else { if ( current_d == ' u ' ) i -= 1 ; else if ( current_d == ' d ' ) i += 1 ; else if ( current_d == ' l ' ) j -= 1 ; else if ( current_d == ' r ' ) j += 1 ; } } return new int [ ] { current_i , current_j } ; } public static void main ( String [ ] args ) { int M = 3 ; int N = 5 ; int [ ] [ ] arr = { { 0 , 1 , 1 , 1 , 0 } , { 1 , 0 , 1 , 0 , 1 } , { 1 , 1 , 1 , 0 , 0 } } ; int [ ] p = endpoints ( arr , M , N ) ; System . out . print ( " ( " + p [ 0 ] + " , ▁ " + p [ 1 ] + " ) " + "NEW_LINE"); } }