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
function isSafe ( N , M , str ) { var coll = 0 , colr = 0 , rowu = 0 , rowd = 0 ; for ( var i = 0 ; i < str . length ; i ++ ) { if ( str [ i ] == ' ' ) { coll ++ ; if ( colr > 0 ) { colr -- ; } if ( coll == M ) { break ; } } else if ( str [ i ] == ' ' ) { colr ++ ; if ( coll > 0 ) { coll -- ; } if ( colr == M ) { break ; } } else if ( str [ i ] == ' ' ) { - rowu ++ ; if ( rowd > 0 ) { rowd -- ; } if ( rowu == N ) { break ; } } else if ( str [ i ] == ' ' ) { rowd ++ ; if ( rowu > 0 ) { rowu -- ; } if ( rowd == N ) { break ; } } } if ( Math . abs ( rowd ) < N && Math . abs ( rowu ) < N && Math . abs ( coll ) < M && Math . abs ( colr ) < M ) { return true ; } return false ; } var N = 1 , M = 1 ; var str = " " ; if ( isSafe ( N , M , str ) ) document . write ( " " ) ; else document . write ( " " ) ;