Print all paths from a source point to all the 4 corners of a Matrix | Function to check if we reached on of the entry / exit ( corner ) point . ; Function to check if the index is within the matrix boundary . ; Recursive helper function ; If any corner is reached push the string t into ans and return ; For all the four directions ; The new ith index ; The new jth index ; The direction R / L / U / D ; If the new cell is within the matrix boundary and it is not previously visited in same path ; mark the new cell visited ; Store the direction ; Backtrack to explore other paths ; Function to find all possible paths ; Create a direction array for all the four directions ; stores the result ; Initialise variable ; function call ; Print the result
function isCorner ( i , j , M , N ) { if ( ( i == 0 && j == 0 ) || ( i == 0 && j == N - 1 ) || ( i == M - 1 && j == N - 1 ) || ( i == M - 1 && j == 0 ) ) return true ; return false ; } function isValid ( i , j , M , N ) { if ( i < 0 i >= M j < 0 j >= N ) return false ; return true ; } function solve ( i , j , M , N , Dir , maze , t , ans ) { if ( isCorner ( i , j , M , N ) ) { ans . push ( t ) ; return ; } for ( let k = 0 ; k < 4 ; k ++ ) { let x = i + Dir [ k ] [ 0 ] ; let y = j + Dir [ k ] [ 1 ] ; let c = Dir [ k ] [ 2 ] ; if ( isValid ( x , y , M , N ) && maze [ x ] [ y ] == 1 ) { maze [ x ] [ y ] = 0 ; t += c ; solve ( x , y , M , N , Dir , maze , t , ans ) ; t = t . substr ( 0 , t . length - 1 ) ; maze [ x ] [ y ] = 1 ; } } return ; } function possiblePaths ( src , maze ) { let Dir = [ [ - 1 , 0 , " " ] , [ 0 , 1 , " " ] , [ 1 , 0 , " " ] , [ 0 , - 1 , " " ] , ] ; let temp = " " ; let ans = [ ] ; solve ( src [ 0 ] , src [ 1 ] , maze . length , maze [ 0 ] . length , Dir , maze , temp , ans ) ; return ans ; } let maze = [ [ 1 , 0 , 0 , 1 , 0 , 0 , 1 , 1 ] , [ 1 , 1 , 1 , 0 , 0 , 0 , 1 , 0 ] , [ 1 , 0 , 1 , 1 , 1 , 1 , 1 , 0 ] , [ 0 , 0 , 0 , 0 , 1 , 0 , 0 , 0 ] , [ 1 , 0 , 1 , 0 , 1 , 0 , 0 , 1 ] , [ 0 , 1 , 1 , 1 , 1 , 0 , 0 , 1 ] , [ 0 , 1 , 0 , 0 , 1 , 1 , 1 , 1 ] , [ 1 , 1 , 0 , 0 , 0 , 0 , 0 , 1 ] , ] ; let src = [ 4 , 2 ] ; let paths = possiblePaths ( src , maze ) ; if ( paths . length == 0 ) { document . write ( " " ) ; } else { for ( let i = 0 ; i < paths . length ; i ++ ) { if ( paths [ i ] ) document . write ( paths [ i ] + " " ) ; } }