Possibility of moving out of maze | Function to check whether it will stay inside or come out ; marks all the positions that is visited ; Initial starting point ; initial assumption is it comes out ; runs till it is inside or comes out ; if the movement is towards left then we move left . The start variable and mark that position as visited if not visited previously . Else we break out ; It will be inside forever ; If the movement is towards right , then we move right . The start variable and mark that position as visited if not visited previously else we break out ; it will be inside forever ; Driver code
function checkingPossibility ( a , n , s ) { let mark = new Array ( a [ 0 ] * n ) ; mark . fill ( 0 ) ; let start = 0 ; let possible = 1 ; while ( start >= 0 && start < n ) { if ( s == " " ) { if ( mark [ start ] == 0 ) { mark [ start ] = 1 ; start -= a [ start ] ; } else { possible = 0 ; break ; } } else { if ( mark [ start ] == 0 ) { mark [ start ] = 1 ; start += a [ start ] ; } else { possible = 0 ; break ; } } } if ( possible == 0 ) document . write ( " " + " " ) ; else document . write ( " " ) ; } let n = 2 ; let s = " " ; let a = [ 1 , 2 ] ; checkingPossibility ( a , n , s ) ;