Coordinates of the last cell in a Matrix on which performing given operations exits from the Matrix | 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 ; Number of rdows ; Number of columns ; Given matrix arr [ ] [ ]
function issafe ( m , n , i , j ) { if ( i < 0 ) return false ; if ( j < 0 ) return false ; if ( i >= m ) return false ; if ( j >= n ) return false ; return true ; } function endpoints ( arr , m , n ) { let i = 0 ; let j = 0 ; let current_i = 0 ; let current_j = 0 ; let current_d = ' ' ; let rcd = new Map ( ) ; rcd . set ( ' ' , ' ' ) ; rcd . set ( ' ' , ' ' ) ; rcd . set ( ' ' , ' ' ) ; rcd . set ( ' ' , ' ' ) ; while ( issafe ( m , n , i , j ) ) { current_i = i ; current_j = j ; if ( arr [ i ] [ j ] == 1 ) { let move_in = rcd . get ( current_d ) ; arr [ i ] [ j ] = 0 ; if ( move_in == ' ' ) i -= 1 ; else if ( move_in == ' ' ) i += 1 ; else if ( move_in == ' ' ) j -= 1 ; else if ( move_in == ' ' ) j += 1 ; current_d = move_in ; } else { if ( current_d == ' ' ) i -= 1 ; else if ( current_d == ' ' ) i += 1 ; else if ( current_d == ' ' ) j -= 1 ; else if ( current_d == ' ' ) j += 1 ; } } return [ current_i , current_j ] ; } let M = 3 ; let N = 5 ; let arr = [ [ 0 , 1 , 1 , 1 , 0 ] , [ 1 , 0 , 1 , 0 , 1 ] , [ 1 , 1 , 1 , 0 , 0 ] ] ; let p = endpoints ( arr , M , N ) ; document . write ( " " + p [ 0 ] + " " + p [ 1 ] + " " + " " ) ;