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 rows ; Number of columns ; Given matrix arr [ ] [ ]
def issafe ( m , n , i , j ) : NEW_LINE INDENT if i < 0 : NEW_LINE INDENT return False NEW_LINE DEDENT if j < 0 : NEW_LINE INDENT return False NEW_LINE DEDENT if i >= m : NEW_LINE INDENT return False NEW_LINE DEDENT if j >= n : NEW_LINE INDENT return False NEW_LINE DEDENT return True NEW_LINE DEDENT def endpoints ( arr , m , n ) : NEW_LINE INDENT i = 0 NEW_LINE j = 0 NEW_LINE current_d = ' r ' NEW_LINE rcd = { ' l ' : ' u ' , ' u ' : ' r ' , ' r ' : ' d ' , ' d ' : ' l ' } NEW_LINE while issafe ( m , n , i , j ) : NEW_LINE INDENT current_i = i NEW_LINE current_j = j NEW_LINE if arr [ i ] [ j ] == 1 : NEW_LINE INDENT move_in = rcd [ current_d ] NEW_LINE arr [ i ] [ j ] = 0 NEW_LINE if move_in == ' u ' : NEW_LINE INDENT i -= 1 NEW_LINE DEDENT elif move_in == ' d ' : NEW_LINE INDENT i += 1 NEW_LINE DEDENT elif move_in == ' l ' : NEW_LINE INDENT j -= 1 NEW_LINE DEDENT elif move_in == ' r ' : NEW_LINE INDENT j += 1 NEW_LINE DEDENT current_d = move_in NEW_LINE DEDENT else : NEW_LINE INDENT if current_d == ' u ' : NEW_LINE INDENT i -= 1 NEW_LINE DEDENT elif current_d == ' d ' : NEW_LINE INDENT i += 1 NEW_LINE DEDENT elif current_d == ' l ' : NEW_LINE INDENT j -= 1 NEW_LINE DEDENT elif current_d == ' r ' : NEW_LINE INDENT j += 1 NEW_LINE DEDENT DEDENT DEDENT return ( current_i , current_j ) NEW_LINE DEDENT M = 3 NEW_LINE N = 5 NEW_LINE arr = [ [ 0 , 1 , 1 , 1 , 0 ] , [ 1 , 0 , 1 , 0 , 1 ] , [ 1 , 1 , 1 , 0 , 0 ] , ] NEW_LINE print ( endpoints ( arr , M , N ) ) NEW_LINE