Check if the robot is within the bounds of the grid after given moves | Function that returns true if the robot is safe ; If current move is " L " then increase the counter of coll ; If value of coll is equal to column then break ; If current move is " R " then increase the counter of colr ; If value of colr is equal to column then break ; If current move is " U " then increase the counter of rowu ; If value of rowu is equal to row then break ; If current move is " D " then increase the counter of rowd ; If value of rowd is equal to row then break ; If robot is within the bounds of the grid ; Unsafe ; Driver code
def isSafe ( N , M , str ) : NEW_LINE INDENT coll = 0 NEW_LINE colr = 0 NEW_LINE rowu = 0 NEW_LINE rowd = 0 NEW_LINE for i in range ( len ( str ) ) : NEW_LINE INDENT if ( str [ i ] == ' L ' ) : NEW_LINE INDENT coll += 1 NEW_LINE if ( colr > 0 ) : NEW_LINE INDENT colr -= 1 NEW_LINE DEDENT if ( coll == M ) : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT elif ( str [ i ] == ' R ' ) : NEW_LINE INDENT colr += 1 NEW_LINE if ( coll > 0 ) : NEW_LINE INDENT coll -= 1 NEW_LINE DEDENT if ( colr == M ) : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT elif ( str [ i ] == ' U ' ) : NEW_LINE INDENT rowu += 1 NEW_LINE if ( rowd > 0 ) : NEW_LINE INDENT rowd -= 1 NEW_LINE DEDENT if ( rowu == N ) : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT elif ( str [ i ] == ' D ' ) : NEW_LINE INDENT rowd += 1 NEW_LINE if ( rowu > 0 ) : NEW_LINE INDENT rowu -= 1 NEW_LINE DEDENT if ( rowd == N ) : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT DEDENT if ( abs ( rowd ) < N and abs ( rowu ) < N and abs ( coll ) < M and abs ( colr ) < M ) : NEW_LINE INDENT return True NEW_LINE DEDENT return False NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 1 NEW_LINE M = 1 NEW_LINE str = " R " NEW_LINE if ( isSafe ( N , M , str ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT