Print the indices for every row of a grid from which escaping from the grid is possible | Function to find the row index for every row of a matrix from which one can exit the grid after entering from left ; Iterate over the range [ 0 , M - 1 ] ; Stores the direction from which a person enters a cell ; Row index from which one enters the grid ; Column index from which one enters the grid ; Iterate until j is atleast N - 1 ; If Mat [ i ] [ j ] is equal to 1 ; If entry is from left cell ; Decrement i by 1 ; Assign ' D ' to dir ; If entry is from upper cell ; Decrement j by 1 ; Assign ' R ' to dir ; If entry is from right cell ; Increment i by 1 ; Assign ' U ' to dir ; If entry is from bottom cell ; Increment j by 1 ; Assign ' L ' to dir ; Otherwise , ; If entry is from left cell ; Increment i by 1 ; Assign ' U ' to dir ; If entry is from upper cell ; Increment j by 1 ; Assign ' L ' to dir ; If entry is from right cell ; Decrement i by 1 ; Assign ' D ' to dir ; If entry is from lower cell ; Decrement j by 1 ; Assign ' R ' to dir ; If i or j is less than 0 or i is equal to M or j is equal to N ; If j is equal to N ; Otherwise ; Input ; Function call
def findPath ( arr , M , N ) : NEW_LINE INDENT for row in range ( M ) : NEW_LINE INDENT dir = ' L ' NEW_LINE i = row NEW_LINE j = 0 NEW_LINE while ( j < N ) : NEW_LINE INDENT if ( arr [ i ] [ j ] == 1 ) : NEW_LINE INDENT if ( dir == ' L ' ) : NEW_LINE INDENT i -= 1 NEW_LINE dir = ' D ' NEW_LINE DEDENT elif ( dir == ' U ' ) : NEW_LINE INDENT j -= 1 NEW_LINE dir = ' R ' NEW_LINE DEDENT elif ( dir == ' R ' ) : NEW_LINE INDENT i += 1 NEW_LINE dir = ' U ' NEW_LINE DEDENT elif ( dir == ' D ' ) : NEW_LINE INDENT j += 1 NEW_LINE dir = ' L ' NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT if ( dir == ' L ' ) : NEW_LINE INDENT i += 1 NEW_LINE dir = ' U ' NEW_LINE DEDENT elif ( dir == ' U ' ) : NEW_LINE INDENT j += 1 NEW_LINE dir = ' L ' NEW_LINE DEDENT elif ( dir == ' R ' ) : NEW_LINE INDENT i -= 1 NEW_LINE dir = ' D ' NEW_LINE DEDENT elif ( dir == ' D ' ) : NEW_LINE INDENT j -= 1 NEW_LINE dir = ' R ' NEW_LINE DEDENT DEDENT if ( i < 0 or i == M or j < 0 or j == N ) : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT if ( j == N ) : NEW_LINE INDENT print ( i , end = " ▁ " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( - 1 , end = " ▁ " ) NEW_LINE DEDENT DEDENT DEDENT arr = [ [ 1 , 1 , 0 , 1 ] , [ 1 , 1 , 0 , 0 ] , [ 1 , 0 , 0 , 0 ] , [ 1 , 1 , 0 , 1 ] , [ 0 , 1 , 0 , 1 ] ] NEW_LINE M = len ( arr ) NEW_LINE N = len ( arr [ 0 ] ) NEW_LINE findPath ( arr , M , N ) NEW_LINE