Check if a path exists from a given cell to any boundary element of the Matrix with sum of elements not exceeding K | Function to check if it is valid to move to the given index or not ; Otherwise return false ; Function to check if there exists a path from the cell ( X , Y ) of the matrix to any boundary cell with sum of elements at most K or not ; Base Case ; If K >= board [ X ] [ Y ] ; Stores the current element ; Mark the current cell as visited ; Visit all the adjacent cells ; Mark the cell unvisited ; Return false ; Driver code
function isValid ( board , i , j , K ) { if ( board [ i ] [ j ] <= K ) { return true ; } return false ; } function findPath ( board , X , Y , M , N , K ) { if ( X < 0 X == M Y < 0 Y == N ) { return true ; } if ( isValid ( board , X , Y , K ) ) { let board_XY = board [ X ] [ Y ] ; board [ X ] [ Y ] = Number . MAX_VALUE ; if ( findPath ( board , X + 1 , Y , M , N , K - board_XY ) || findPath ( board , X - 1 , Y , M , N , K - board_XY ) || findPath ( board , X , Y + 1 , M , N , K - board_XY ) || findPath ( board , X , Y - 1 , M , N , K - board_XY ) ) { return true ; } board [ X ] [ Y ] = board_XY ; } return false ; } let grid = [ [ 25 , 5 , 25 , 25 , 25 , 25 ] , [ 25 , 1 , 1 , 5 , 12 , 25 ] , [ 25 , 1 , 12 , 0 , 15 , 25 ] , [ 22 , 1 , 11 , 2 , 19 , 15 ] , [ 25 , 2 , 2 , 1 , 12 , 15 ] , [ 25 , 9 , 10 , 1 , 11 , 25 ] , [ 25 , 25 , 25 , 25 , 25 , 25 ] ] ; let K = 17 ; let M = grid . length ; let N = grid [ 0 ] . length ; let X = 2 , Y = 3 ; if ( findPath ( grid , X , Y , M , N , K ) ) document . write ( " " ) ; else document . write ( " " ) ;